树状数组 hdu2838 Cow Sorting

一看到这个就应该能想到逆序对把。。。。

我的第一想法就是,假如我们现在在考虑第i个数字,我们需要统计在[1,i-1]里面有多少个数字大于A[i],以及[1,i-1]中大于A[i]的数字之和

大于A[i]的数字之和相当于X的积累,[1,i-1]里面有多少个数字大于A[i]记为m,第i个数字至少要交换m次,m*A[i]就相当于Y的积累

然后再全部积累一下,,这题就做完了

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1e5 + 5;
const int INF = 0x3f3f3f3f;

LL A[MX], B[MX];

LL sum(LL *S, int x) {
    LL ret = 0;
    for(; x; x -= x & -x) {
        ret += S[x];
    }
    return ret;
}

LL query(LL *S, int L, int R) {
    return sum(S, R) - sum(S, L - 1);
}

void update(LL *S, int x, int d) {
    for(; x < MX; x += x & -x) {
        S[x] += d;
    }
}


int main() {
    //freopen("input.txt", "r", stdin);
    int n, t;
    while(~scanf("%d", &n)) {
        memset(A, 0, sizeof(A));
        memset(B, 0, sizeof(B));

        scanf("%d", &t);

        update(A, t, 1);
        update(B, t, t);

        LL ans = 0;
        for(int i = 2; i <= n; i++) {
            scanf("%d", &t);
            ans += query(A, t + 1, MX - 1) * t;
            ans += query(B, t + 1, MX - 1);
            update(A, t, 1);
            update(B, t, t);
        }
        printf("%I64d\n", ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值