首页 > 代码库 > hdu 2838 Cow Sorting(树状数组)
hdu 2838 Cow Sorting(树状数组)
Cow Sorting
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2239 Accepted Submission(s): 711
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.
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.
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
7HintInput 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到N打乱,要求把数组重新有序(从小到大),只能交换相邻的两个数字,代价为相邻两个数字和。求最小代价?
一个数字必须和前面比它大的数字交换,还要和后面比它小的数字交换。
#include"stdio.h" #include"string.h" #define N 100005 #define lowbit(i) (i&(-i)) __int64 a[N]; //记录数字和 int c[N],n; //记录数字个数 void add(int x,int d1,int d2) { while(x<=n) { a[x]+=d1; c[x]+=d2; x+=lowbit(x); } } int sum1(int x) //求比x小的数字已经出现几个(包括x) { int s=0; while(x>0) { s+=c[x]; x-=lowbit(x); } return s; } __int64 sum2(int x) { __int64 s=0; while(x>0) { s+=a[x]; x-=lowbit(x); } return s; } int main() { int i,x; __int64 k1,ans; while(scanf("%d",&n)!=-1) { ans=0; memset(a,0,sizeof(a)); memset(c,0,sizeof(c)); for(i=1;i<=n;i++) { scanf("%d",&x); add(x,x,1); k1=i-sum1(x); //x前面有几个比它大的数字 if(k1!=0) { ans+=k1*x; ans+=sum2(n)-sum2(x); //求比x大的数字和 } } printf("%I64d\n",ans); } return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。