hdoj Cow Sorting 2838 (树状数组)

来源:互联网 发布:js从后往前截字符串 编辑:程序博客网 时间:2024/05/21 17:36

Cow Sorting

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2820    Accepted Submission(s): 929


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
3231

Sample Output
7
Hint
Input DetailsThree cows are standing in line with respective grumpiness levels 2, 3, and 1.Output Details2 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).
 
#include<stdio.h>#include<string.h>#define N 100010#define ll __int64int n;struct zz{int cnt;ll sum;}q[N<<2];ll lobit(int x){return x&(-x);}int update(int gen,int v){while(gen<=n){q[gen].sum+=v;q[gen].cnt+=1;gen+=lobit(gen);}return 0;}int query(int gen)//返回x前面比x小的元素的个数 {int ans=0;while(gen>0){ans+=q[gen].cnt;gen-=lobit(gen);}return ans;}ll querys(int gen)//返回x前面所有数的和 {ll ans=0;while(gen>0){ans+=q[gen].sum;gen-=lobit(gen);}return ans;}int main(){int i,x;while(scanf("%d",&n)!=EOF){ll ans=0;memset(q,0,sizeof(q));for(i=1;i<=n;i++){scanf("%d",&x);update(x,x);ll k=i-query(x);//k表示有多少个数是逆序的 if(k!=0){ll kk=querys(n)-querys(x);//前n个数之和减去比x大的数即为所求。 ans+=k*x+kk;}}printf("%I64d\n",ans);}return 0;}

0 0
原创粉丝点击