首页 > 代码库 > HDU Cow Sorting (树状数组)
HDU Cow Sorting (树状数组)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2838
Cow Sorting
Problem Description
Sherlock‘s N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock‘s milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.
Please help Sherlock calculate the minimal time required to reorder the cows.
Input
Line 1: A single integer: N
Lines 2..N + 1: Each line contains a single integer: line i + 1 describes the grumpiness of cow i.
Output
Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.
Sample Input
3
2
3
1
Sample Output
7
Hint
Input Details
Three cows are standing in line with respective grumpiness levels 2, 3, and 1.
Output Details
2 3 1 : Initial order.
2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4).
1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).
1 #include<stdio.h> 2 #include<string.h> 3 #define ll __int64 4 ll c[100000+5],v[100000+5]; 5 int n; 6 int Lowbit(int k) 7 { 8 return (k&-k); 9 }10 void update(int pos,int num,int val)11 {12 while(pos<=n)13 {14 c[pos]+=num;15 v[pos]+=val;16 pos+=Lowbit(pos);17 }18 }19 ll sum_count(int pos)20 {21 ll s=0;22 23 while(pos>0)24 {25 s+=c[pos];26 pos-=Lowbit(pos);27 }28 return s;29 }30 ll sum(int pos)31 {32 ll s=0;33 34 while(pos>0)35 {36 s+=v[pos];37 pos-=Lowbit(pos);38 }39 return s;40 }41 int main()42 {43 int i,x;44 while(scanf("%d",&n)!=-1)45 {46 memset(c,0,sizeof(c));47 memset(v,0,sizeof(v));48 ll ans=0,k2,k1;49 for(i=1;i<=n;i++)50 {51 scanf("%d",&x);52 update(x,1,x);53 k1=i-sum_count(x);///到此为止 比x大的个数;54 /*sum_count[x] 为输入i个数的时候 x之前有sum_count[x]个比x小的数 用i相减则为大于x的个数*/55 if(k1!=0)56 {57 k2=sum(n)-sum(x);///到此为止 比x大的数的和;58 ans+=x*k1+k2;///到此为止 比x大的数与x交换之后的和;59 }60 }61 printf("%I64d\n",ans);62 }63 return 0;64 }
/*坑爹的题 必须用 __int64 不能用long long 不能用int ╮(╯▽╰)╭*/