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

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

传送门

题意:

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

题解:

这题其实就是树状数组求逆序对的推广。树状数组是肯定可以做的,我这里用了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;
}


转载于:https://www.cnblogs.com/na7-TRZNDP-Z/p/9782444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值