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.
10 1 3 6 9 0 8 5 7 4 2
16
看了好久才明白题意 英语真的好差劲的说
下面有一个解析 非常的清楚 :
说一下线段树做法
O(nlogn)
:
以这个序列来说明:
1,9,2,3,0,8,5,7,4,6
我们先假设有一个长度为n元素全为0的数组:
0,0,0,0,0,0,0,0,0,0
我们先计算所给序列的第一项1(实际上是第0项)的数字所对应位置之后所有元素的和(括号里面的数),和就是当前与这个数逆序的数的个数,这样做避免了重复统计逆序对,我们把它累计起来:
0,(0,0,0,0,0,0,0,0,0),sum+=0;
我们将所给序列的第一项的数字所对应位置置1:
0,1,0,0,0,0,0,0,0,0
第二项9:
0,1,0,0,0,0,0,0,0,(0),sum+=0;
0,1,0,0,0,0,0,0,0,1
第三项2:
0,1,(0,0,0,0,0,0,0,1),sum+=1;
(2与9逆序)
0,1,1,0,0,0,0,0,0,1
第四项3:
0,1,1,(0,0,0,0,0,0,1),sum+=1;
(3与9逆序)
0,1,1,1,0,0,0,0,0,1
第五项0:
(0,1,1,1,0,0,0,0,0,1),sum+=4;
(0与1,2,3,9逆序)
1,1,1,1,0,0,0,0,0,1
以此类推到最后,sum便是该序列逆序对个数。
现在考虑循环同构序列的最小值:
刚才的序列:
1,9,2,3,0,8,5,7,4,6
我们把x0 = 1移到最后:
9,2,3,0,8,5,7,4,6,1
发现逆序对增加了8对(8 = 10 - x0 - 1),减少了1对(1 = x0),可以推出结论,向后移动一个数字,逆序对增加n - xi - 1,减少xi。扫一遍维护最小值即可
附上 我的蒟蒻 代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
#define maxn 100000
int tre[maxn*10];
int a[maxn];
void build(int in,int l,int r){ //这里白写了
if(l==r){
tre[in]=0;
return ;
}
int mid=(l+r)/2;
build(in*2,l,mid);
build(in*2+1,mid+1,r);
}
int query(int in,int l,int r,int x,int y){
if(l==x&&y==r){
return tre[in];
}
int mid=(x+y)/2;
if(l>mid){
return query(in*2+1,l,r,mid+1,y);
}
if(r<=mid){
return query(in*2,l,r,x,mid);
}
return query(in*2+1,mid+1,r,mid+1,y)+query(in*2,l,mid,x,mid);
}
void updata(int in,int l,int r,int rt){
if(l==r){
tre[rt]=1; //一定要等于1 不然会错
return ;
}
int mid=(l+r)/2;
if(in<=mid){
updata(in,l,mid,rt*2);
}
else updata(in,mid+1,r,rt*2+1);
tre[rt]=tre[rt*2]+tre[rt*2+1];
}
int main(){
int n;
while(cin>>n&&n){
memset(tre,0,sizeof(tre));
int sum=0;
for(int j=1;j<=n;j++){
scanf("%d",a+j);
sum+=query(1,a[j]+1,n,1,n); //注意 如果 a[j]==0 的情况 所以要 +1 可以用纸写一下
//cout<<sum<<endl;
updata(a[j]+1,1,n,1);
}
int k=sum;
for(int j=1;j<=n;j++){
k+=(n-2*a[j]-1);
sum=min(sum,k);
}
//if(sum<0) sum=0;
cout<<sum<<endl;
}
return 0;
}