题解 CF1042D 【Petya and Array】

· · 题解

题解 CF1042D 【Petya and Array】

这道题其实要求的就是\sum^n_{r=1}\sum^{r-1}_{l=1}\sum^r_{i=l}a[i] < t 的(l,r)对数量

时间复杂度O(n^3)

可以用前缀和优化到O(n^2)

可是还是无法AC

怎么办呢?

我们可以这样:

注意:开始时要把0扔进树状数组!!!(原因:sum[0]=0)

Code:

#include <bits/stdc++.h>

#define lowbit(x) (x & (-x))

const int MaxN = 200010;

int n;
int cnt;
long long t;
int c[MaxN << 2];
long long a[MaxN], s[MaxN];
std::map<long long, int>m;

int query(int x)
{
    int ans = 0;
    while(x)
        ans += c[x], x -= lowbit(x);
    return ans;
}

void add(int x, int val)
{
    while(x <= cnt)
        c[x] += val, x += lowbit(x);
}

int main()
{
    scanf("%d%lld", &n, &t);
    m[0] = 1;
    for(int i = 1; i <= n; i++)
        scanf("%lld", &a[i]), s[i] = s[i - 1] + a[i], m[s[i] - t] = m[s[i]] = 1;//前缀和
    for(std::map<long long, int>::iterator it = m.begin(); it != m.end(); it++)
        it -> second = ++cnt;//离散化
    long long ans = 0;
    add(m[0], 1);
    for(int i = 1; i <= n; i++)
    {
        ans += i - query(m[s[i] - t]);//计入答案
        add(m[s[i]], 1);//更新
    }  
    printf("%lld", ans);
    return 0;
}