Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 24067 Accepted Submission(s): 14252
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.
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5+5; int bit[maxn]; int a[maxn]; int n; int lowbit(int x){ return x&-x; } int sum(int i){ int ans=0; while(i>0){ ans+=bit[i]; i-=lowbit(i); } return ans; } void update(int i){ while(i<=n){ bit[i]++; i+=lowbit(i); } } int main(){ while(scanf("%d",&n) !=EOF){ memset(bit,0,sizeof(bit)); long long ans=0; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); a[i]++; ans+=sum(n)-sum(a[i]); update(a[i]); } long long minn=ans; for(int i=1;i<=n;i++){ ans+=n-a[i]-(a[i]-1); minn=min(ans,minn); } printf("%lld\n",minn); } }
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5+5; int a[maxn]; int b[maxn]; int c[maxn]; int n; int ans; void mergsort(int l,int r){ if(l==r) return; int mid=(l+r)>>1; mergsort(l,mid); mergsort(mid+1,r); int i=l; int j=mid+1; int pos=0; while(i<=mid&&j<=r){ if(a[i]<=a[j]) b[pos++]=a[i++]; else{ b[pos++]=a[j++]; ans+=(mid-i+1); } } while(i<=mid) b[pos++]=a[i++]; while(j<=r) b[pos++]=a[j++]; for(i=0;i<pos;i++) a[i+l]=b[i]; } int main(){ int n; while(~scanf("%d",&n)){ for(int i=0;i<n;i++){ scanf("%d",&a[i]); c[i]=a[i]; } ans=0; mergsort(0,n-1); int minn=ans; for(int i=0;i<n;i++){ ans+=(n-c[i]-1-c[i]); minn=min(minn,ans); } cout<<minn<<endl; } }