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
题意:求一个排列的逆序对数,然后移动这个排列得到的新排列最小的逆序对
模板题
线段树区间内数字出现的次数和,当加入一个a[ i ]时查询他右边的数字出现的次数;
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn=5005;
int n;
int b[maxn<<2];
int a[maxn];
void build(int l,int r,int rt)
{
b[rt]=0;
if(l==r) return ;
int mid=(l+r)>>1;
build(l,mid,rt*2);
build(mid+1,r,rt*2+1);
}
void add(int l,int r,int rt,int v)
{
b[rt]+=1;
if(l==r)
{
return ;
}
int mid=(l+r)>>1;
if(v<=mid) add(l,mid,rt*2,v);
else add(mid+1,r,rt*2+1,v);
}
int sum(int l,int r,int rt,int ll,int rr)
{
if(ll<=l&&r<=rr) return b[rt];
int mid=(l+r)>>1;
int ans=0;
if(ll<=mid) ans+=sum(l,mid,rt<<1,ll,rr);
if(rr>mid) ans+=sum(mid+1,r,rt<<1|1,ll,rr);
return ans;
}
int main()
{
int v;
while(~scanf("%d",&n))
{
build(1,n,1);
int ans=0;
for(int i=1;i<=n;++i)
{
scanf("%d",&a[i]);
++a[i];
}
for(int i=1;i<=n;i++)
{
ans+=sum(1,n,1,a[i],n);//1到a[i]右边界的元素个数即是所求
add(1,n,1,a[i]);//a[i]右边界
}
int mmin=ans;
for(int i=1;i<=n;++i)
{
ans-=a[i]-1;
ans+=n-a[i];
mmin=min(ans,mmin);
}
cout<
你可能感兴趣的:(线段树)