Minimum Inversion Number
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.
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
题目大意 :
给定一个N和关于0-N-1的序列,通过不断把首元素放到最后得出变换后的序列和其逆序数,
求出最小逆序数(包括一开始那个序列)。
思 路:利用线段树存储,可以找出初始序列的逆序数。
(这点很重要,根据线段树统计离散化的数,便于查找和存储,根据已经统计的数可以统计出
当前比某个数大的个数。)
之后对于每个数的逆序数,根据上一次的逆序数ans 推得
anns=ans--data[i]+n-data[i]-1;
首先减去data[i]作为队首存在data[i]-1 个数比data[i]小 再加上将data[i] 置于最后n-data[i]
个数比data[i] 大 .这一点需要临场推理。
代码如下:
/*踏实!!努力!!*/
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
#include<map>
#include<queue>
#include<stack>
using namespace std;
#define N 5050
int sum[N*4],n,data[N];
void build(int l,int r,int cur)
{
sum[cur]=0;
if(l==r)
return ;
int mid=(l+r)>>1;
build(l,mid,cur<<1);
build(mid+1,r,cur<<1|1);
return ;
}
int query(int curL,int curR,int l,int r,int cur)
{
if(curL<=l&&curR>=r)
return sum[cur];
int ans=0;
int mid=(l+r)>>1;
if(curL<=mid)
ans+=query(curL,curR,l,mid,cur<<1);
if(curR>mid)
ans+=query(curL,curR,mid+1,r,cur<<1|1);
return ans;
}
void upDate(int val,int l,int r,int cur)
{
if(l==r){
sum[cur]+=1;
return ;
}
int mid=(l+r)>>1;
if(val<=mid)
upDate(val,l,mid,cur<<1);
else
upDate(val,mid+1,r,cur<<1|1);
sum[cur]=sum[cur<<1]+sum[cur<<1|1];
return ;
}
int main()
{
while(scanf("%d",&n)!=EOF){
int count=0,ans;
build(0,n-1,1);
for(int i=1;i<=n;i++){
scanf("%d",&data[i]);
count+=query(data[i],n-1,0,n-1,1);
upDate(data[i],0,n-1,1);
}
ans=count;
for(int i=1;i<=n;i++){
ans+=(n-data[i]-data[i]-1);
count=min(ans,count);
}
printf("%d\n",count);
}
return 0;
}