Minimum Inversion Number
Time Limit: 1000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 139464-bit integer IO format: %I64d Java class name: Main
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.
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
Source
解题:求逆序数,很有意思的是算出原序列的逆序值后,只要加上 n - 1 - x - x就表示数列循环左移一位的逆序数值!只有从0开始且是连续的才成立。
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 5005; 4 5 int d[maxn],tree[maxn<<2],n; 6 void update(int L,int R,int id,int v) { 7 if(id <= L && id >= R) { 8 tree[v]++; 9 return; 10 } 11 int mid = (L + R)>>1; 12 if(id <= mid) update(L,mid,id,v<<1); 13 if(id > mid) update(mid+1,R,id,v<<1|1); 14 tree[v] = tree[v<<1] + tree[v<<1|1]; 15 } 16 int query(int L,int R,int lt,int rt,int v){ 17 if(lt <= L && rt >= R) return tree[v]; 18 int mid = (L + R)>>1,ans = 0; 19 if(lt <= mid) ans += query(L,mid,lt,rt,v<<1); 20 if(rt > mid) ans += query(mid+1,R,lt,rt,v<<1|1); 21 return ans; 22 } 23 int main() { 24 while(~scanf("%d",&n)) { 25 memset(tree,0,sizeof tree); 26 int ans = 0,tmp = 0; 27 for(int i = 0; i < n; ++i) { 28 scanf("%d",d+i); 29 tmp += query(0,n-1,d[i],n-1,1); 30 update(0,n-1,d[i],1); 31 } 32 ans = tmp; 33 for(int i = 0; i < n; ++i){ 34 tmp += n - 1 - d[i] - d[i]; 35 ans = min(ans,tmp); 36 } 37 printf("%d ",ans); 38 } 39 return 0; 40 }