标签:
Description:
Input:
Output:
Sample Input:
Sample Output:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int INF=0x3f3f3f3f; const int N=5010; struct node { int left, right, num; }no[4*N]; int Min; void Bulid(int left, int right, int root) { int mid; no[root].left = left; no[root].right = right; no[root].num = 0; if (left == right) return ; mid = (left+right)/2; Bulid(left, mid, root*2); Bulid(mid+1, right, root*2+1); } void Insert(int p, int root) ///插入数据时就可以统计逆序数的个数 { int mid; no[root].num++; if (no[root].left == no[root].right) return ; mid = (no[root].left+no[root].right)/2; if (p <= mid) { Min += no[root*2+1].num; Insert(p, root*2); } else Insert(p, root*2+1); } int main () { int i, n, p[N], ans; while (scanf("%d", &n) != EOF) { Bulid(0, n-1, 1); Min = 0; for (i = 1; i <= n; i++) { scanf("%d", &p[i]); Insert(p[i], 1); } ans = Min; for (i = 1; i <= n; i++) { Min += (n-1-p[i]) - p[i]; ///首位移到最后一位时,逆序数加上那些比它大的数的个数,减去那些比它小的数的个数(因为该序列的元素都是0~n-1) ans = min(ans, Min); } printf("%d\n", ans); } return 0; }
HDU 1394 Minimum Inversion Number
标签:
原文地址:http://www.cnblogs.com/syhandll/p/4732602.html