标签:
Description
Input
Output
Sample Input
Sample Output
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAX = 5555; struct segtree{ int left; int right; int val; }tt[MAX << 2]; void build(int n, int left ,int right) { tt[n].left = left; tt[n].right = right; tt[n].val = 0; if(left == right) return ; int mid = (tt[n].left + tt[n].right) >> 1; build(n << 1, left, mid); build(n << 1|1, mid + 1, right); } int query(int n, int left ,int right) { if(tt[n].left == left && tt[n].right == right) return tt[n].val;//根节点 int mid = (tt[n].left + tt[n].right) >> 1; if(right <= mid) return query(n << 1, left ,right); else if(left > mid) return query(n << 1|1, left, right); else return query(n << 1,left, mid) + query(n << 1|1, mid + 1,right); } void update(int n, int idx) { tt[idx].val++; if(tt[idx].left == tt[idx].right) return ; int mid = (tt[idx].left + tt[idx].right) >> 1; if( n <= mid ) update(n, idx << 1); else update(n , idx << 1|1); } int main() { int n,a[MAX], ans ; while(~scanf("%d",&n)){ build(1, 0, n - 1 ); int sum = 0; for(int i = 0; i < n ; i++){ scanf("%d", &a[i]); sum += query(1,a[i],n - 1); update(a[i],1); } ans = sum; for(int i = 0; i < n ; i++){ sum = sum - a[i] + (n - 1 - a[i]); ans = min(ans, sum); } printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zero-begin/p/4330199.html