CodeForces1024 Petya and Array(cdq分治/树状数组)

CodeForces1024 Petya and Array(cdq分治/树状数组)

传送门

题意:

给你长度为n的序列,问你有多少个子区间和小于等于tt

题解:

这题其实就是树状数组求逆序对的推广。树状数组是肯定可以做的,我这里用了cdq分治的方法做了(感觉难敲了挺多)。

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;
long long ans=0;
long long t;
long long sum[maxn],temp[maxn];
void cdq(int l,int r)
{
	if(l==r)
	{
		if(sum[l]<t) ans++;
		return;
	}
	int mid=(l+r)>>1;
	cdq(l,mid);cdq(mid+1,r);
	int i=l,j=mid+1,tot=l;
	while(i<=mid||j<=r)
	{
		if(sum[i]<sum[j])
		{
			int num=lower_bound(sum+j+1,sum+r+1,sum[i]+t)-sum-j-1;
			ans+=num+1;
			if(sum[j+num]>=sum[i]+t) ans--;
			temp[tot++]=sum[i++];
		}
		else
		{
			int num=upper_bound(sum+i+1,sum+mid+1,sum[j]-t)-sum-i-1;
			ans+=(mid-i+1-num);
			if(sum[num+i]+t<=sum[j]) ans--;
			temp[tot++]=sum[j++];
		}
		if(i>mid)
		{
			while(j<=r)
			{
				temp[tot++]=sum[j++];
			}
		}
		else if(j>r)
		{
			while(i<=mid)
			{
				temp[tot++]=sum[i++];
			}
		}
	}
	for(i=l;i<=r;i++)
		sum[i]=temp[i];
}
int main()
{
	#ifdef TEST
		freopen("input.txt","r",stdin);
    #endif
	int T,n,m,i,j,k;
	scanf("%d%lld",&n,&t);
	for(i=1;i<=n;i++)
	{
		scanf("%d",&k);
		sum[i]=sum[i-1]+k;
	}
	cdq(1,n);
	cout<<ans<<endl;
}


posted on 2018-09-19 16:16  TRZNDP_Z  阅读(106)  评论(0编辑  收藏  举报

导航