HDU 2838

来源:互联网 发布:数据机房建设方案 编辑:程序博客网 时间:2024/04/30 15:52
Cow Sorting

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

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).

//这题是树状数组逆序数的应用

//逆序数:每个元素a[i]前面有多少个元素大于a[i] 并且个数相加得的结果是逆序数 例如:2 3 1  0+0+2=2;

//此题符合冒泡排序 最少代价的交换就是 小的数值不要放到大的数值后  

//所以每个元素符合交换的最小代价=(比a[i]大的个数)*a[i]+sum(i) (sum(i)指的是比a[i]大的数之和)  例:2*1+5=7

#include <stdio.h>#include <cstring>__int64 n,c[100010];  //注意用__int64  __int64 cnt[100010];__int64 lowbit(__int64 x){    return x&(-x);}void add(__int64  i,__int64  x,__int64  c[]){    while(i<=n)    {        c[i]+=x;        i+=lowbit(i);    }}__int64  sum(__int64  i,__int64  c[]){    __int64  sum=0;    while(i)    {        sum+=c[i];        i-=lowbit(i);    }    return sum;}int main(){    while(~scanf("%I64d",&n))    {        __int64  a,s=0;        memset(c,0,sizeof(c));        memset(cnt,0,sizeof(cnt));        for(int i=1;i<=n;i++)        {            scanf("%I64d",&a);            add(a,a,c);            add(a,1,cnt);  //计算个数 sum(a,cnt)求的是比a小的 i-sum(a,cnt)比它大的个数            s+=(i-sum(a,cnt))*a+(sum(n,c)-sum(a,c));        }        printf("%I64d\n",s);    }    return 0;}




0 0
原创粉丝点击