hdu1394
Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8178 Accepted Submission(s): 5022
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<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int a[5005];
struct Node
{
int l,r,num;
} tree[50000];
void Build(int i,int l,int r)
{
tree[i].l = l;
tree[i].r = r;
tree[i].num = 0;
if(l == r)
{
return;
}
int mid = (l+ r) / 2;
Build(2*i,l,mid);
Build(2*i+1,mid+1,r);
}
void updata(int i,int x)
{
int l = tree[i].l;
int r = tree[i].r;
int mid = (l + r) / 2;
if(x == l && x == r)
{
tree[i].num ++;
return;
}
if(x <= mid)
updata(2*i,x);
else
updata(2*i+1,x);
tree[i].num = tree[2*i].num + tree[2*i+1].num;
}
int Query(int n,int x,int y)
{
int l = tree[n].l;
int r = tree[n].r;
int mid = (l + r) / 2;
int ans = 0;
if(x == l && y == r)
return tree[n].num;
if(y<= mid)
ans += Query(2*n,x,y);
else if(x> mid)
ans += Query(2*n+1,x,y);
else
ans+=Query(2*n,x,mid)+Query(2*n+1,mid+1,y);
return ans;
}
int main()
{
int n,sum,ans;
int i,j;
while(scanf("%d",&n) != EOF)
{
sum = 0;
Build(1,0,n);
for(i = 1; i <= n; i++)
{
scanf("%d",&a[i]);
updata(1,a[i]);
sum += Query(1,a[i]+1,n);
}
ans = sum;
for(i = 1; i <=n; i++)
{
sum = sum + (n - 1 - a[i]) - a[i];
ans=min(ans,sum);
}
printf("%d\n",ans);
}
return 0;
}