HDU 2838

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值