codeforces round#520 D. Petya and Array

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[200010];
ll sum[200010];//前缀和数组 
ll c[200010];//树状数组 
ll n,t;
ll ask(int x)//查询前缀和 
{
   ll ans=0;
   for(;x;x-=x & (-x)) ans+=c[x];
   return ans;
}
void add(int x,int y)
{
	for(;x<=n+1;x+=x&-x) c[x]+=y;//这里第一位是0,1到 n+1代表n个前缀和的值(离散化后) 
}
int main()
{
	scanf("%lld%lld",&n,&t);
	for(int i=1;i<=n;i++)
	   scanf("%lld",&a[i]);
	for(int i=1;i<=n;i++)
	{
		a[i]+=a[i-1];
		sum[i]=a[i];
	}//将sum[i]排序离散化 
	sort(sum,sum+n+1);
	ll ans=0;
	for(int i=1;i<=n;i++)
	{
	    int tmp=lower_bound(sum,sum+n+1,a[i-1])-sum;//离散化,找到前缀和在sum数组里面的位置 
	    add(tmp+1,1);//这里树状数组维护的第一位是0出现的次数,第1到n+1位是前缀和在每位出现的次数,tmp代表离散化之后的前缀和 ,tmp+1是这个值对应到树状数组中的位置 
	    tmp=lower_bound(sum,sum+n+1,a[i]-t+1)-sum;//这里想要计算sum[j]>sum[i]-t的数字有多少个先算sum[j]<=sum[i]-t的个数(用upper_bound),再用总数i-1减去ask()-1 
	    ans+=(i-ask(tmp));
	}
	printf("%lld
",ans);
}

  

原文地址:https://www.cnblogs.com/lishengkangshidatiancai/p/10147781.html