思路:可以先求开始序列的逆序数,一开始记录每个叶子节点的值为0,然后对于每个数,插入之后更新一下,对于当前的x[i],需要插叙[x[i], n - 1]之间的数已经出现了多少个。求出一开始的逆序数之后,就可以通过递推关系式以此找出后面的逆序数对。
/***************************************** Author :Crazy_AC(JamesQi) Time :2015 File Name : *****************************************/ // #pragma comment(linker, "/STACK:1024000000,1024000000") #include <iostream> #include <algorithm> #include <iomanip> #include <sstream> #include <string> #include <stack> #include <queue> #include <deque> #include <vector> #include <map> #include <set> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <limits.h> using namespace std; #define MEM(a,b) memset(a,b,sizeof a) typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> ii; const int inf = 1 << 30; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; inline int Readint(){ char c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); } return x; } const int maxn = 5010; 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 mid = (L + R) >> 1; Build(L,mid,rt << 1); Build(mid + 1,R,rt << 1 | 1); return ; } void updata(int L,int R,int rt,int p){ if (L == R){ sum[rt]++; return ; } int mid = (L + R) >> 1; if (p <= mid) updata(L,mid,rt << 1,p); else updata(mid + 1,R,rt << 1 | 1,p); pushup(rt); return; } int Query(int L,int R,int rt,int l,int r){ if (l <= L && R <= r){ return sum[rt]; } int mid = (L + R) >> 1; int res = 0; if (l <= mid) res += Query(L,mid,rt << 1,l,r); if (r > mid) res += Query(mid + 1,R,rt << 1 | 1,l,r); return res; } int n,num[maxn]; int main() { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); while(~scanf("%d",&n)){ for (int i = 0;i < n;i++) num[i] = Readint(); Build(0,n - 1,1); int sum = 0; for (int i = 0;i < n;i++){ sum += Query(0,n - 1,1,num[i],n - 1); updata(0,n - 1,1,num[i]); } int ans = sum; for (int i = 0;i < n;i++){ sum += (n - num[i] - 1) - num[i]; ans = min(ans,sum); } printf("%d\n",ans); } return 0; }