HDU 4000 Fruit Ninja 【树状数组】

题意:给1-N的一个排列,找出所有的(x, y, z) 使得x < z < y,求这样的元组有多少个?

题解:对于每个x,只需要找到比x靠后,而且比x大的数的个数,这样的组合数为:n*(n-1)/2

这里面有重复的情况:i < j < k, 而且a[i] < a[j] < a[k],那么对于y,只需要找到比y小且出现在y前面的数的个数,和比y大,且出现在y后边的数的个数。



树状数组统计x之前出现的比x小的个数,剩下的就全部可以算出来了。

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
#define N 100010
typedef long long ll;
#define mod 100000007ll

int n, a[N];
inline int lowbit(int x) { return x & (-x); }
int sum(int x) {
    int ret = 0;
    while (x >= 1) {
        ret += a[x];
        x -= lowbit(x);
    }
    return ret;
}
void add(int x) {
    while (x <= n) {
        a[x]++;
        x += lowbit(x);
    }
}
int main() {
    int T, t;
    ll ans, s, p;
    scanf("%d", &T);

    for (int cas=1; cas<=T; cas++) {
        scanf("%d", &n);
        memset(a, 0, sizeof(a));

        ans = 0, s = 0;
        for (int i=0; i<n; i++) {
            scanf("%d", &t);
            p = sum(t);
            ans = (ans + (ll)(n-t-i+p)*(n-t-i+p-1)/2) % mod;
            s = (s + (ll)(n-t-i+p)*p) % mod;
            add(t);
        }
        printf("Case #%d: %I64d\n", cas, (ans+mod-s) % mod);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值