HDU 2838 Cow Sorting(树状数组应用)

题意:

            不翻译了~

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.

题解:

每次交换只能相邻交换(冒泡排序)。只不过这里的求的不是最小交换次数(逆序数),而是每个点有个权值,每次交换花费X+Y(X,Y为权值)。求所有的花费最低。和求序列最小逆序数一样,从头扫一遍就行。由于相邻交换,所以每次刚一出现存在逆序的元素都应该立即交换才能保证最小。只不过现在的树状数组要开两个,一个求前面有多少个逆序数,另外一个求前面比它大的元素总和。

 

#include<bits/stdc++.h>

using namespace std;

const int maxn = 100111;

long long c[2][maxn];

void add(int i,int x,long long v)
{
    while(x<maxn)
    {
        c[i][x] += v;
        x+=(x&-x);
    }
}

long long sum(int i,int x)
{
    long long res = 0;
    while(x>0)
    {
        res+=c[i][x];
        x-=(x&-x);
    }
    return res;
}

int main()
{
    int n;
    cin>>n;
    
        //memset(c,0,sizeof c);
        long long ans=0;
        for(int i=1;i<=n;i++)
        {
            int x;
            scanf("%d",&x);
            long long q= (i-1-sum(0,x));///多少个值比x大
          //  long long w= (i-1-sum(1,x));
            long long w=sum(1,maxn)-sum(1,x);///比x大的值 和为多少
            ans+=q*x+w;
            add(0,x,1);
            add(1,x,x);
        }
        cout<<ans<<endl;
    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值