Cow Sorting (树状数组)

Cow Sorting

Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 4
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).

Source
2009 Multi-University Training Contest 3 - Host by WHU


题意:给出n个数,将这n个数按照升序排列,每次排序只可以调换相邻的两个数,则权值为这两个数的和,将

           n个数按照升序排列后,输出所有权值的加和

题解:对于一个数x,设左边有n个数比它大,则这n个数必须移动x右边去,则需要的代价为这n个数的和+x*n,相当于求逆序数。

           ans+=Sum(n,c)-Sum(a[i],c)+(Sum(n,d)-Sum(a[i],d))*a[i];  //Sum(n,c)-Sum(a[i],c)表示a[i]到n即比a[i]的数的和


#include<stdio.h>   
#define lowbit(i) (i)&(-i)   
__int64 n,a[100005],ans;  
__int64 c[100005],d[100005],i;//c保存比x小的数的和,d保存比x小的数的个数    
void Add(__int64 i,__int64 val,__int64 c[])  
{  
    for(;i<=100001;i+=lowbit(i)) c[i]+=val;  
}  
__int64 Sum(__int64 i,__int64 c[])  
{  
    __int64 ret=0;  
    for(;i>0;i-=lowbit(i)) ret+=c[i];  
    return ret;  
}  
int main()  
{  
    scanf("%I64d",&n);  
    for(i=0;i<n;i++) scanf("%I64d",&a[i]);  
    for(i=0;i<n;i++)  
    {  
        Add(a[i],a[i],c);  
        Add(a[i],1,d);  
        ans+=Sum(n,c)-Sum(a[i],c)+(Sum(n,d)-Sum(a[i],d))*a[i];  
    }  
    printf("%I64d\n",ans);  
    return 0;  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值