CodeForces1024 Petya and Array (cdq partition / Fenwick tree)

CodeForces1024 Petya and Array (cdq partition / Fenwick tree)

Portal

Meaning of the questions:

Give you a sequence of length n, you have to ask how many subintervals and less than or equal t t

answer:

This question is actually seeking to promote Fenwick tree on the reverse. Fenwick tree is certainly possible to do, I use a divide and conquer method cdq do (feel hard to knock a lot).

#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;
}


Published 51 original articles · won praise 6 · views 6329

Guess you like

Origin blog.csdn.net/weixin_40859716/article/details/82773867