题解 CF1042D 【Petya and Array】
这道题其实要求的就是 的对数量
时间复杂度
可以用前缀和优化到
可是还是无法AC
怎么办呢?
我们可以这样:
-
由于,所以离散化
-
扫一遍,对于每个i,使用树状数组统计前面的有多少个位置满足的,将计入答案
-
将加入树状数组
注意:开始时要把扔进树状数组!!!(原因:)
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;
}