这个题是求
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)
这些序列中,最小的逆序数。
以前用归并排序和树状数组写过,但是基本都忘完了 T T 。。。这个在线段树分类下的,可以拿线段树做。
首先先求出原序列的逆序数,这个可以用线段树去求。
从a[0]开始扫描,找比a[0]大的个数,也就是询问区间(a[0],n-1)中点的个数,然后再插入a[0],更新父节点即可。
因为我还是用线段代表数字的,所以插入的是长度为1的线段。
有个结论,设逆序数为sum,a[0]后面比它小的一定是a[0]个。那么移到末尾后,比a[0]大的数的后面比它小的数统统加一,也就是加(n - a[0] - 1),然后它放到末尾了,他原来的后面比它大的数变为0,也就是sum = sum + (n - a[0] - 1) - a[0];
线段树,好神奇~~~
#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define BUG puts("here!!!")
using namespace std;
const int MAX = 5010;
struct Tnode{ int l,r,sum;};
Tnode node[MAX<<2];
int a[MAX];
void init()
{
memset(node,0,sizeof(node));
}
void Build(int t,int l,int r)
{
node[t].l = l; node[t].r = r;
node[t].sum = 0;
if( node[t].l == node[t].r - 1 ) return ;
int mid = MID(l,r);
Build(L(t),l,mid);
Build(R(t),mid,r);
}
void Updata(int t,int l,int r)
{
if( node[t].l == l && node[t].r == r )
{
node[t].sum = 1;
return ;
}
if( node[t].l == node[t].r - 1 ) return ;
int mid = MID(node[t].l,node[t].r);
if( l <= mid )
Updata(L(t),l,r);
if( r > mid )
Updata(R(t),l,r);
node[t].sum = node[R(t)].sum + node[L(t)].sum;
}
int Query(int t,int l,int r)
{
if( node[t].l >= l && node[t].r <= r )
return node[t].sum;
if( node[t].l == node[t].r - 1 ) return 0;
int mid = MID(node[t].l,node[t].r);
int ans = 0;
if( l <= mid )
ans += Query(L(t),l,r);
if( r > mid )
ans += Query(R(t),l,r);
return ans;
}
int main()
{
int n,len;
while( ~scanf("%d",&n) )
{
int sum = 0;
init();
Build(1,0,n+1);
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
sum += Query(1,a[i]+1,n+1);
Updata(1,a[i],a[i]+1);
}
int mmin = sum;
for(int i=0; i<n; i++)
{
sum = sum + n - 2*a[i] - 1;
mmin = min(sum,mmin);
}
printf("%d\n",mmin);
}
return 0;
}