Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 16258 Accepted Submission(s): 9890
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.
10 1 3 6 9 0 8 5 7 4 2
16
最近一直在学线段树,跟着大神的讲义。被这道题卡住了(尽管写的爆搜也过了,数据量不大),查了资料之后想通了。为了印象深刻所以写下来,希望能让更多的童鞋明白。
分析:这道题的难点主要有两个:①:怎么求最初的逆序数(逆序数的定义不说了) ②知道最初的逆序数之后怎么递推出其它的从而求出最小值。
②比较容易理解,先说②:
比如你有五个数(记住只能是由0-4组成的) 分别为:3 0 2 4 1 如果把3移到最后一位,增加的逆序数和减少的逆序数分别是多少?
无论后面四个数的顺序是怎样的,是不是一定有一个数(4)比3大,有三个数(0,1,2)比3小,把3移到最后一位的过程中,是不是增加了一个逆序数的同时,减少了三个逆序数?
如果是n个数呢? a1,a2,a3.....an 如果把a1移到最后一位,是不是一定是减少了a1个逆序数,同时增加了n-1-a1个逆序数。也就是说,设原来逆序数个数为sum1,当前为sum2,那么就有sum2=sum1+n-1-ai-ai
接下来说①,用线段树求最初的逆序数。
首先你必须要明白的一点是,线段树维护的区间代表什么。要注意,这里的叶节点代表的不是数组下标,而是数本身!
这样说可能不是很容易理解。
这么说吧,如果用爆搜,你会怎么求逆序数的个数?还是原来的例子,3 0 2 4 1,是不是依次记录在3前面比3大的数,再记录在0前面比0大的数...最后再加起来?
线段树也是一个道理,它需要维护的是,这个区间上,作为逆序的那个数,一共被用了多少次。
还是举原来的例子 3 0 2 4 1,一步一步来。
我们首先建立一个空树,每个节点都是0.
然后更新,首先输入3,找到所有包含3的区间,把它加为1.
接着输入0。首先是查询[0,4]这个区间,发现比0大的数就是3一个,所以sum+1。然后更新,把包括了0的区间+1.
接着输入2,先查询[2,4]这个区间,发现只有3这一个数,sum+1。然后更新,把包含了2的区间加1,也就是说,要是接下来有查询[2,4]这个区间,结果就是2.
然后输入4,查询结果肯定是0.然后更新包含4的区间。
最后输入1.查询[1,4]区间,发现结果为3,sum+3,然后更新。
代码是最初照着大神的代码写的 ,如下:
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <queue>
#include <ctype.h>
#include <vector>
#include <queue>
#include <set>
using namespace std;
#define MAXN 5010
#define INF 1000000
#define MOD 23333
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1 //也就是rt*2(+1)
int sum[MAXN<<2];
void pushUp(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];//左二子和右儿子的和,向上更新
}
void build(int l,int r,int rt)
{
sum[rt]=0;
if(l==r)
return;
int m=(l+r)/2;
build(lson);
build(rson);
}
void update(int p,int l,int r,int rt)
{
if(l==r){
sum[rt]++;
return;
}
int m=(l+r)>>1;
if(p<=m)
update(p,lson);
else
update(p,rson);
pushUp(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
return sum[rt];
int m=(l+r)>>1;
int ret=0;
if(L<=m)
ret+=query(L,R,lson);
if(R>m)
ret+=query(L,R,rson);
return ret;
}
int a[MAXN];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
build(0,n-1,1);
int ret,sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",a+i);
sum+=query(a[i],n-1,0,n-1,1);
update(a[i],0,n-1,1);
}
ret=sum;
for(int i=0;i<n;i++)
{
sum+=n-2*a[i]-1;
ret=min(ret,sum);
}
printf("%d\n",ret);
}
}