Codeforces Round 510 D. Petya and Array (树状数组)

1042D

给出一个数组a,问存在多少对l, r满足i < j且\sum_{i = l}^{r}a_{i}<t

从l 到r 的和小于t,即sum(r)-sum(l-1)<t,其中sum是a的前缀和。实现的方法就是从前往后对于每一个sum(i),看在它前面有多少个大于sum(i)-t的前缀和。

这个过程用树状数组来维护,每次加入sum(i-1),然后查询sum(i)。这样可以保证每次查询sum(i)的时候,存在于树状数组中的必然是在i之前的前缀和。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 200050;
const ll INF = (1LL << 62) - 1;
const double eps = 1e-8;

int n;
ll a[maxn], b[maxn], tree[maxn], t;
int lowbit(int x) {return x & (-x);}

void add(int x)
{
    while(x <= (n + 1))
    {
        tree[x]++;
        x += lowbit(x);
    }
}

ll query(int x)
{
    ll res = 0;
    while(x > 0)
    {
        res += tree[x];
        x -= lowbit(x);
    }
    return res;
}

int main()
{
    scanf("%d%I64d", &n, &t);
    for(int i = 1;i <= n;i++)
    {
        scanf("%I64d", &a[i]);
        a[i] += a[i-1];
        b[i] = a[i];
    }
    sort(b, b + n + 1);
    ll ans = 0;
    for(int i = 1;i <= n;i++)
    {
        int tmp = lower_bound(b, b + n+1, a[i - 1]) - b;
        add(tmp + 1);
        tmp = lower_bound(b, b + n + 1, a[i] - t+1) - b;
        ans += i - query(tmp);
    }
    printf("%I64d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/NPU_SXY/article/details/82774417