标签:
1 #include <stdio.h> 2 #include <algorithm> 3 4 using namespace std; 5 6 int a[5005]; 7 struct Node{ 8 int l,r,num; 9 }tree[50000]; 10 11 void Build(int n,int x,int y){ 12 tree[n].l = x; 13 tree[n].r = y; 14 tree[n].num = 0; 15 if(x == y){ 16 return; 17 } 18 int mid = (x + y) / 2; 19 Build(2*n,x,mid); 20 Build(2*n+1,mid+1,y); 21 } 22 23 void Modify(int n,int x){ 24 int l = tree[n].l; 25 int r = tree[n].r; 26 int mid = (l + r) / 2; 27 if(x == l && x == r){ 28 tree[n].num = 1; 29 return; 30 } 31 if(x <= mid) Modify(2*n,x); 32 else Modify(2*n+1,x); 33 tree[n].num = tree[2*n].num + tree[2*n+1].num; 34 } 35 36 int Query(int n,int x,int y){ 37 int l = tree[n].l; 38 int r = tree[n].r; 39 int mid = (l + r) / 2; 40 int ans = 0;; 41 if(x == l && y == r) 42 return tree[n].num; 43 if(x <= mid) ans += Query(2*n,x,min(mid,y)); 44 if(y > mid) ans += Query(2*n+1,max(mid+1,x),y); 45 return ans; 46 } 47 int main(){ 48 //freopen ("a.txt" , "r" , stdin ) ; 49 int n,sum,ans; 50 int i,j; 51 52 while(scanf("%d",&n) != EOF){ 53 sum = 0; 54 Build(1,0,n); 55 for(i = 1;i <= n;i++){ 56 scanf("%d",&a[i]); 57 Modify(1,a[i]); 58 sum += Query(1,a[i]+1,n); 59 } 60 ans = sum; 61 for(i = 1;i < n;i++){ 62 sum = sum + (n - 1 - a[i]) - a[i]; 63 if(sum < ans) 64 ans = sum; 65 } 66 printf("%d\n",ans); 67 } 68 }
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4277985.html