[HDU] 1394 Minimum Inversion Number [线段树求逆序数]

时间:2023-02-05 03:15:13

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11788    Accepted Submission(s): 7235

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
 
Author
CHEN, Gaoli
 
Source
 
Recommend
Ignatius.L
 
题解:这题的维护信息为每个数是否已经出现。每次输入后,都从该点的值到n-1进行查询,每次发现出现了一个数,由于是从该数的后面开始找的,这个数肯定是比该数大的。那就是一对逆序数,然后逆序数+1.最后求完所有的逆序数之后,剩下的就可以递推出来了。因为假如目前的第一个数是x,那当把他放到最后面的时候,少的逆序数是本来后面比他小的数的个数。多的逆序数就是放到后面后前面比他大的数的个数。因为所有数都是从0到n-1.所以比他小的数就是x,比他大的数就是n-1-x。这样的话每次的逆序数都可以用O(1)的时间计算出来。然后找最小的时候就可以了。
 
 #include<cstdio>
#include<algorithm> using namespace std; #define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1 const int maxn = + ;
int sum[maxn<<]; void PushUp(int rt)
{
sum[rt]=sum[rt<<]+sum[rt<<|];
} void build(int l,int r,int rt)
{
int m; sum[rt]=;
if(l==r) {
return;
}
m=(l+r)>>;
build(lson);
build(rson);
} int query(int L,int R, int l, int r,int rt)
{
int m,ret; if(L<=l && r<=R) {
return sum[rt];
} m=(l+r) >> ;
ret=;
if(L<=m) ret+=query(L,R,lson);
if(R>m) ret+=query(L,R,rson); return ret;
} void Updata(int p,int l,int r,int rt)
{
int m;
if (l==r) {
sum[rt]++;
return ;
}
m=(l+r)>>;
if(p<=m) Updata(p,lson);
else Updata(p,rson); PushUp(rt);
} int main()
{
int n,sum,x[maxn]; while(~scanf("%d",&n)) {
sum=;
build(,n-,); for(int i = ;i < n;i++) {
scanf("%d",&x[i]);
sum+=query(x[i],n-,,n-,);
Updata(x[i],,n-,);
}
int ret=sum;
for(int i=;i<n;i++) {
sum+=n-x[i]-x[i]-;
ret=min(ret,sum);
} printf("%d\n",ret);
} return ;
}