跳到正文

题解

题解 CF1042D 【Petya and Array】

little_sun约 2 分钟
原文
文章信息与版本

文章信息

发布
2018年11月23日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 2 分钟
获赞
11
题目
CF1042D

版本

  1. v1当前

题解 CF1042D 【Petya and Array】

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

时间复杂度O(n3)O(n^3)

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

可是还是无法AC

怎么办呢?

我们可以这样:

  • 由于∣t∣≤1014|t|\leq10^{14},所以离散化

  • 扫一遍1−n1-n,对于每个i,使用树状数组统计前面的有多少个位置满足sum[j−1]≤sum[i]−tsum[j-1]\leq sum[i]-t的,将i−cnti-cnt计入答案

  • 将sum[i]sum[i]加入树状数组

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

Code:

C++
#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;
}
原文
存档评论3 条抓取于