HDU 1394 Minimum Inversion Number
2015-08-09 16:44
351 查看
Minimum Inversion Number
[align=left]Problem Description[/align]The
inversion number of a given number sequence a1, a2, ..., an is the
number of pairs (ai, aj) that satisfy i < j and ai > aj.
For
a given sequence of numbers a1, a2, ..., an, if we move the first m
>= 0 numbers to the end of the seqence, we will obtain another
sequence. There are totally n such sequences as the following:
a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
[align=left]Input[/align]
The
input consists of a number of test cases. Each case consists of two
lines: the first line contains a positive integer n (n <= 5000); the
next line contains a permutation of the n integers from 0 to n-1.
[align=left]Output[/align]
For each case, output the minimum inversion number on a single line.
[align=left]Sample Input[/align]
10
1 3 6 9 0 8 5 7 4 2
[align=left]Sample Output[/align]
16
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct segtree { int l,r; int num; int mid() { return (l+r)>>1; } }; segtree tree[5005<<2]; int a[5005<<2]; void PushUp(int rt) { tree[rt].num=tree[rt<<1].num+tree[rt<<1|1].num; } void build(int l,int r,int rt) { tree[rt].l=l; tree[rt].r=r; tree[rt].num=0; if(l==r)return; int m=tree[rt].mid(); build(l,m,rt<<1); build(m+1,r,rt<<1|1); } int query(int l,int r,int rt) { if(tree[rt].l==l&&tree[rt].r==r) return tree[rt].num; int m=tree[rt].mid(); if(r<=m) return query(l,r,rt<<1); else if(l>m) return query(l,r,rt<<1|1); else return query(l,m,rt<<1)+query(m+1,r,rt<<1|1); } void update(int pos,int rt) { if(tree[rt].l==tree[rt].r) { tree[rt].num++; return; } int m=tree[rt].mid(); if(pos<=m)update(pos,rt<<1); else update(pos,rt<<1|1); PushUp(rt); } int main() { int n,i,j; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;i++) scanf("%d",&a[i]); build(0,n-1,1); int sum=0; for(i=0;i<n;i++) { sum+=query(a[i],n-1,1); update(a[i],1); } int ans=999999999; ans=min(ans,sum); for(i=0;i<n;i++) { sum=sum-a[i]+n-1-a[i]; ans=min(ans,sum); } printf("%d\n",ans); } return 0; }
相关文章推荐
- BZOJ3459 : Bomb
- C++ class与内存
- hdu 3593 分类: hdu 2015-0...
- Grep用法
- 通过SQLServer的数据库邮件来发送邮件
- GC垃圾收集算法
- LeetCode(20)Valid Parentheses
- LeetCode(141)(142) Linked List Cycle I II
- hdu 3593
- windowsphone8.1学习笔记之应用数据(二)
- hdu 3593 分类: hdu 2015-08-09 16:43 12人阅读 评论(0) 收藏
- LeetCode(20)Valid Parentheses
- leetcode_242——Valid Anagram (字典法)
- 第三周工作周报
- java synchronized静态同步方法与非静态同步方法,同步语句块
- ListView上拉加载更多
- Java回顾之I/O
- php框架laravel学习 二 (数据库建立迁移与建模)
- UVA 152 Tree's a Crowd
- 二叉搜索树的基本操作(查找、插入、删除)【数据结构】