HDU 1394 Minimum Inversion Number
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
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.
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.
Input
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.
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.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10 1 3 6 9 0 8 5 7 4 2
Sample Output
16 解题思路: 1,题目的意思是给你一个n,然后是一段包含0~n-1全部数字的序列,然后有一个操作 把前面的数放到后面来,这样的操作可以形成n个序列,让你求出这样所有的逆序序列里最小的逆序数 2,一个数列逆序数的求法有归并排序(不介绍)然后就是树状数组了 3,树状数组实现求取逆序数:把树状数组当做标记数组使用,从后往前输入每一个数据计算出现了多少个 比这个数小的数的个数因为树状数组可以快速求和,这样就可以在nlogn的时间复杂度内求得逆序数了 4,然后就是怎么根据第一个求得的下一个状态的逆序数了 5,对于开头的第一个数,如果这个数放在后面,首先逆序数会减少【后面有多少个比他小的数的个数】, 加到后面会导致逆序数增加【前面有多少个比他大的】,由于这里包含了所有的0~n-1的数,所以很容易求得所有的逆序数。 6,然后简单的代码实现就可以了。///树状数组求逆序数 #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 5005 ; int C[4*maxn] ; int n ;///节点总数 int lowbit(int x){return x&-x;} int sum(int x){ int ret = 0 ; while(x>0){ ret+=C[x]; x-=lowbit(x) ; } return ret ; } void add(int x,int d){ while(x<=n){ C[x]+=d ; x+=lowbit(x) ; } return ; } int num[maxn] ; int x[maxn] ; int main(){ while(~scanf("%d",&n)){ memset(C,0,sizeof(C)) ; memset(num,0,sizeof(num)) ; for(int i=0;i<n;i++){ scanf("%d",&x[i]); x[i]++ ; } //printf("yes\n"); int ans = 0 ; for(int i=n-1;i>=0;i--){ //printf("i = %d\n",i); num[i] = sum(x[i]); ans+=num[i] ; //printf("ans = %d\n",ans); add(x[i],1) ; } //printf("ans=%d\n",ans); //printf("yes2\n"); int temp = ans ; for(int i=0;i<n;i++){ temp=temp-(x[i]-1)+(n-x[i]); ans = min(temp,ans); } printf("%d\n",ans); } return 0; }