hdu 1394 树状数组版!!!

//树状数组版 #include<stdio.h> #include<string.h> #define N 5005 int tree[N]; int arr[N]; int lowbit(int x){ return x&(x^(x-1)); } int get_sum(int k) { int sum = 0; while(k >= 1){ sum += tree[k]; k -= lowbit(k); } return sum; } void change(int k) { while(k <= N){ tree[k] += 1; k += lowbit(k); } } int main() { int n; int i; int count; int min; int flag; while(scanf("%d",&n) == 1){ count = 0; memset(tree,0,sizeof(tree)); for(i = 1;i <= n;i++){ scanf("%d",&arr[i]); count += i-1-get_sum(arr[i]); change(arr[i]+1); } min = count; for(i = 1;i <= n-1;i++){ flag = get_sum(arr[i]); count = count-flag+(n-1-flag); if(count < min) min = count; } printf("%d/n",min); } return 0; }

你可能感兴趣的:(tree)