Minimum Inversion Number_线段树||树状数组

时间:2023-03-08 22:21:23
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

【题意】给出n个数,求其在第一个数到最后一个的过程中,最小的逆序数是多少

【思路】建立一颗空树,在插入每个数的时候,统计这个数前面有多少数大于他,当a[i]由第一个变为最后一个时,要加上a[i]后面大于a[i]的数的个数,有n-1-a[i]个,要减去a[i]后面小于a[i]的数的个数,有a[i]个(注意i是从0开始的)

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int N=;
struct node
{
int l,r;
int num; }tree[N*];
void build(int k,int l,int r)//建空树
{
int mid=(l+r)/;
tree[k].l=l;
tree[k].r=r;
tree[k].num=;
if(l==r) return ;
build(k*,l,mid);
build(k*+,mid+,r);
}
void updata(int k,int c)//插入
{
if(tree[k].l==c&&tree[k].r==c)
{
tree[k].num=;
return ;
}
int mid=(tree[k].l+tree[k].r)/;
if(c<=mid)
updata(k*,c);
else updata(k*+,c);
tree[k].num=tree[k*].num+tree[k*+].num;
}
int get_sum(int k,int c,int n)//统计
{
if(c<=tree[k].l&&tree[k].r<=n) return tree[k].num;
else
{
int mid=(tree[k].l+tree[k].r)/;
int sum1=,sum2=;
if(c<=mid)
sum1=get_sum(k*,c,n);
if(n>mid)
sum2=get_sum(k*+,c,n);
return sum1+sum2;
}
} int main()
{
int n;
while(scanf("%d",&n)>)
{
int a[N];
build(,,n-);
int ans=;
for(int i=;i<n;i++)
{
scanf("%d",&a[i]);
ans+=get_sum(,a[i]+,n-);
//每输入一个数时,检验一下先他输入的并比他大的数的个数,对于前面比他大的数来说,他是他们的逆序数
updata(,a[i]);
}
int minx=ans;
for(int i=;i<n;i++)
{
ans=ans+n-*a[i]-; //当a[i]由第一个变为最后一个时,要加上a[i]后面大于a[i]的数的个数,有n-1-a[i]个,要
if(ans<minx) //减去a[i]后面小于a[i]的数的个数,有a[i]个(注意i是从0开始的)
minx=ans;
}
printf("%d\n",minx);
}
return ;
}
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=+;
int a[N],b[N],c[N],ans[N];
int n,cnt,sum;
int lowbit(int x)
{
return x&(-x);
}
int query(int x)
{
int res=;
x++;
while(x<=n)
{
res+=c[x];
x+=lowbit(x);
}
return res;
}
void update(int x)
{
while(x)//对在他前且比他小的数,逆序数加1;
{
c[x]++;
x-=lowbit(x);
}
}
int main()
{
while(~scanf("%d",&n))
{
memset(a,,sizeof(a));
memset(c,,sizeof(c));
int sum=;
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
update(a[i]+);
sum+=query(a[i]+);
}
int tmp=,s=sum;
for(int i=;i<=n;i++)
{
tmp=sum-a[i]+(n-a[i]-);
sum=tmp;
if(tmp<s)
s=tmp;
}
printf("%d\n",s);
}
return ;
}