原题链接:http://codeforces.com/contest/1042/problem/D
Petya and Array
Petya has an array a a a consisting of n n n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t t t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l , r ( l ≤ r ) l,r (l≤r) l,r(l≤r) such hat a l + a l + 1 + ⋯ + a r − 1 + a r < t a_l+a_{l+1}+\cdots+a_{r−1}+a_r<t al+al+1+⋯+ar−1+ar<t.
Input
The first line contains two integers n n n and t ( 1 ≤ n ≤ 200000 , ∣ t ∣ ≤ 2 ⋅ 1 0 14 ) t (1≤n≤200000,|t|≤2⋅10^{14}) t(1≤n≤200000,∣t∣≤2⋅1014).
The second line contains a sequence of integers a 1 , a 2 , ⋯   , a n ( ∣ a i ∣ ≤ 1 0 9 ) a_1,a_2,\cdots,a_n (|a_i|≤10^9) a1,a2,⋯,an(∣ai∣≤109) — the description of Petya’s array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya’s array with the sum of elements less than t t t.
Examples
input
5 4
5 -1 3 4 -1
output
5
input
3 0
-1 2 -3
output
4
input
4 -1
-2 1 -2 3
output
3
Note
In the first example the following segments have sum less than 4 : [ 2 , 2 ] 4:[2,2] 4:[2,2], sum of elements is − 1 [ 2 , 3 ] −1 [2,3] −1[2,3], sum of elements is 2 [ 3 , 3 ] 2 [3,3] 2[3,3], sum of elements is 3 [ 4 , 5 ] 3 [4,5] 3[4,5], sum of elements is 3 [ 5 , 5 ] 3 [5,5] 3[5,5], sum of elements is − 1 −1 −1
题解
区间求和可以转化为前缀和相减,那么对于一个前缀 p r e [ i ] pre[i] pre[i],合法的前缀满足的条件就是 p r e [ i ] − p r e [ j ] < t pre[i]-pre[j]<t pre[i]−pre[j]<t,即查询 p r e [ j ] < p r e [ i ] − t ( 0 ≤ j < i ) pre[j]<pre[i]-t(0\le j<i) pre[j]<pre[i]−t(0≤j<i)的个数,所以我们离散化一下开棵权值线段树即可。
考试的时候调了半天发现忘了先把 0 0 0加进去了。。。
代码
#include<bits/stdc++.h>
#define ll long long
#define ls v<<1
#define rs v<<1|1
using namespace std;
const int M=1e6+5;
int n,q;
ll sum[M],pre[M],data[M],t;
void up(int v){sum[v]=sum[ls]+sum[rs];}
void add(int v,int le,int ri,int pos)
{
if(le==ri){++sum[v];return;}
int mid=le+ri>>1;
if(pos<=mid)add(ls,le,mid,pos);
else add(rs,mid+1,ri,pos);
up(v);
}
int ask(int v,int le,int ri,int lb,int rb)
{
if(lb<=le&&ri<=rb){return sum[v];}
int mid=le+ri>>1;ll ans=0;
if(lb<=mid)ans=ask(ls,le,mid,lb,rb);
if(mid<rb)ans+=ask(rs,mid+1,ri,lb,rb);
return ans;
}
void in()
{
ll ans=0;int l;
scanf("%d%I64d",&n,&t);for(int i=1;i<=n;++i)scanf("%I64d",&pre[i]),pre[i]+=pre[i-1],data[i]=pre[i];
sort(data+1,data+2+n);q=unique(data+1,data+2+n)-data-1;
add(1,1,q,lower_bound(data+1,data+1+q,0)-data);
for(int i=1;i<=n;++i)
{
l=upper_bound(data+1,data+1+q,pre[i]-t)-data;
if(l>q){add(1,1,q,lower_bound(data+1,data+1+q,pre[i])-data);continue;}
ans+=ask(1,1,q,l,q);
add(1,1,q,lower_bound(data+1,data+1+q,pre[i])-data);
}
printf("%I64d",ans);
}
int main(){in();}