题意:求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)
...
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1) 这n个序列的逆序数的最小值。
考虑已经得到第一组序列的逆序数,设第一个数为x,则对于x在第一组序列中将凑出x个逆序数(因为是0~n-1),将第一项移到最后,原来的对第一个数x构成的逆序数对总数就会减少x,而增加的逆序数对就是没有与x构成逆序数对的数量,即n-1-x。那么将x移到最后的操作的贡献就是n-1-2*x。然后求出所有的数的贡献,从第一组序列开始依次遍历过去通过贡献计算该序列的逆序数对即可
#include <bits/stdc++.h>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <time.h>
#include <vector>
#include <cstdio>
#include <string>
#include <iomanip>
///cout << fixed << setprecision(13) << (double) x << endl;
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#define ls rt << 1
#define rs rt << 1 | 1
#define pi acos(-1.0)
#define eps 1e-8
#define Mp(a, b) make_pair(a, b)
#define asd puts("asdasdasdasdasdf");
typedef long long ll;
typedef pair <int, int> pl;
//typedef __int64 LL;
const int inf = 0x3f3f3f3f;
const int N = 5050;
struct node{
int l, r, x;
}tr[N<<2];
int n;
int a[N];
void pushup( int rt )
{
tr[rt].x = tr[ls].x + tr[rs].x;
}
void build( int l, int r, int rt )
{
tr[rt].l = l;
tr[rt].r = r;
tr[rt].x = 0;
if( l == r )
return;
int mid = ( l + r ) >> 1;
build( lson );
build( rson );
}
void update( int rt, int x )
{
if( tr[rt].l == tr[rt].r ) {
tr[rt].x++;
return;
}
int mid = ( tr[rt].l + tr[rt].r ) >> 1;
if( x <= mid )
update( ls, x );
else
update( rs, x );
pushup( rt );
}
int query( int l, int r, int rt )
{
if( l <= tr[rt].l && tr[rt].r <= r )
return tr[rt].x;
int mid = ( tr[rt].l + tr[rt].r ) >> 1;
int res = 0;
if( l <= mid )
res += query( l, r, ls );
if( r > mid )
res += query( l, r, rs );
return res;
}
int main()
{
while( ~scanf("%d", &n) ) {
build( 0, n-1, 1 );
int inv_num = 0, ans;
for( int i = 0; i < n; ++i ) {
scanf("%d", &a[i]);
inv_num += query( a[i]+1, n-1, 1 ); //统计逆序数
update( 1, a[i] );
}
ans = inv_num; //第一个序列逆序数
for( int i = 0; i < n; ++i ) {
inv_num += ( n - 1 - 2 * a[i] ); //每次队首移到队尾逆序数变化量
ans = min( ans, inv_num );
}
printf("%d\n", ans);
}
return 0;
}