hdu1394 Minimum Inversion Number

xiaoxiao2021-02-28  128

Problem 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.   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 就先求第一个顺序的逆序数 。 用线段树求逆序数的方法就是下标代表那个值 0,1代表有没有出现 这样每次查询后面的值之和就是当前值对应的逆序数啦 但是要注意因为从0开始所以建树要从0开始 求玩第一个顺序别的也就好求了 现在把A1从队首挪到队尾 当A1在队首时 后面得数有多少个比它小呢?a1个 挪到队尾A1的逆序数是多少?n-a1-1 #include<bits/stdc++.h> using namespace std; const int maxn=5005; struct node { int l,r,v; }tree[maxn]; int a[maxn]; void build(int i,int l,int r) { tree[i].l=l; tree[i].r=r; if(l==r) { tree[i].v=0; return ; } int m=(l+r)/2; build(i*2,l,m); build(i*2+1,m+1,r); tree[i].v=tree[i*2].v+tree[i*2+1].v; } void update(int i,int x,int v) { if(tree[i].l==tree[i].r) { tree[i].v=1; //cout<<tree[i].l<<endl; return ; } int m=(tree[i].l+tree[i].r)/2; if(x>m)update(i*2+1,x,v); else update(i*2,x,v); tree[i].v=tree[i*2].v+tree[i*2+1].v; } int query(int i,int x,int y) { int sum=0; // cout<<x<<" "<<tree[i].l<<endl; if(x<=tree[i].l&&tree[i].r<=y) { //cout<<"nsdkfjsd"<<endl; //cout<<tree[i].l<<" "<<tree[i].r<<endl; sum+=tree[i].v; return sum; } int m=(tree[i].l+tree[i].r)/2; if(x<=m)sum+=query(i*2,x,y); if(y>m)sum+=query(i*2+1,x,y); return sum; } int main() { int n; while(cin>>n) { build(1,0,n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); } int sum=0; for(int i=1;i<=n;i++) { sum+=query(1,a[i],n); //cout<<i<<" "<<sum<<endl; update(1,a[i],1); } int mmin=sum; for(int i=1;i<=n;i++) { sum-=a[i]; sum+=n-a[i]-1; mmin=min(sum,mmin); } printf("%d\n",mmin); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-20166.html

最新回复(0)