Minimum Inversion Number
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.
InputThe 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.
OutputFor 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 题目大意: ai是0——n-1之间的一个数字,且互不重复; 给你一个长度为n的数列{ai},求以其中某个数为起点的循环队列中的逆序对个数最小; For example: {a1,a2,a3..,an} {a2,a3..,an,a1} {a3,..an,a1,a2} {an,a1,a2,..an-1} Tips: 因为ai是0——n-1之间的一个数字,且互不重复; 所以我们可以知道当ai为开头时,有多少数比它大,有多少数比它小; F[i]表示以第i个数为起点的逆序对个数; 所以先用(线段树|树状数组|归并排序)求出原序列的逆序对数设为F[1]; 所以不难推出F[i]=F[i-1]-a[i-1](有a[i-1]个比它小的数)+n-a[i-1]-1(有n-a[i-1]-1个比它大的数),即F[i]=F[i-1]+n-2*a[i-1]-1; 最后取最小值,输出即可; Code:
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #define MAXN 200008 using namespace std; int ans,n,m,a[MAXN],tree[MAXN],sum; void add(int l,int r,int x,int v){ if(l==r){ tree[v]++; return; } int mid=(l+r) >> 1; if(x<=mid) add(l,mid,x,v<<1); else add(mid+1,r,x,(v<<1)+1); tree[v]=tree[v<<1]+tree[(v<<1)+1]; } int query(int l,int r,int x,int y,int v){ if(l==x&&r==y){ return tree[v]; } int mid=(l+r) >> 1; if(y<=mid) return query(l,mid,x,y,v<<1); if(x>mid) return query(mid+1,r,x,y,(v<<1)+1); return query(l,mid,x,mid,v<<1)+query(mid+1,r,mid+1,y,(v<<1)+1); } int main(){ while(scanf("%d",&n)!=EOF){ memset(tree,0,sizeof(tree)); sum=0; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); a[i]++; sum+=query(1,n,a[i],n,1); add(1,n,a[i],1); } ans=sum; for(int i=1;i<=n-1;i++){ sum=sum-a[i]+1+n-a[i]; ans=min(ans,sum); } printf("%d\n",ans); } }