luogu P3332 [ZJOI2013]K大数查询

背景:

最近 优快云 bug \text{优快云 bug} 优快云 bug好多。
难道这启示我用博客园备份?
今晚就是用来补博客的坑的。

题目传送门:

https://www.luogu.org/problem/P3332

题意:

出题人语文不好?
n n n个位置,每一个位置管理一个数组。
有两种操作:
[ 1 ] [1] [1]:在 [ x , y ] [x,y] [x,y]区间每一个数组内加入一个数 x x x
[ 2 ] [2] [2]:询问 [ x , y ] [x,y] [x,y]区间内的数组构成的所有元素的第 z z z大的数。

思路:

看上去无从下手。
其实想想很简单。
考虑整体二分 ,其实是我不想打树套树
本质上就是将单点修改变成了多点加入。
考虑加入操作的贡献,其实就是 [ l , r ] [l,r] [l,r]区间每一个位置的加入了一个新的元素,其实就可以看做排名 + 1 +1 +1;而询问操作询问一段区间排名的贡献和。
可以用支持区间修改、区间查询的线段树实现。

代码:

注意 long long \text{long long} long long

#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
	int n,m,q,len=0;
	int ans[400010];
	struct node1{int op,id,x,y;LL z;} b[400010],d1[400010],d2[400010];
	struct node2{int l,r,lc,rc,n;LL d,lazy;} tr[200010];
void build(int l,int r)
{
	int now=++len;
	tr[now]=(node2){l,r,-1,-1,r-l+1,0,0};
	if(l<r)
	{
		int mid=(l+r)>>1;
		tr[now].lc=len+1; build(l,mid);
		tr[now].rc=len+1; build(mid+1,r);
	}
}
void update(int now)
{
	if(tr[now].lazy)
	{
		int lc=tr[now].lc,rc=tr[now].rc;
		if(lc!=-1) tr[lc].d+=(LL)tr[lc].n*tr[now].lazy,tr[lc].lazy+=tr[now].lazy;
		if(rc!=-1) tr[rc].d+=(LL)tr[rc].n*tr[now].lazy,tr[rc].lazy+=tr[now].lazy;
		tr[now].lazy=0;
	}
}
void change(int now,int l,int r,int k)
{
	update(now);
	if(tr[now].l==l&&tr[now].r==r)
	{
		tr[now].d+=(LL)tr[now].n*k;
		tr[now].lazy+=k;
		return;
	}
	int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)>>1;
	if(mid+1<=l) change(rc,l,r,k);
	else if(r<=mid) change(lc,l,r,k);
	else change(lc,l,mid,k),change(rc,mid+1,r,k);
	tr[now].d=tr[lc].d+tr[rc].d;
}
LL findsum(int now,int l,int r)
{
	update(now);
	if(tr[now].l==l&&tr[now].r==r) return tr[now].d;
	int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)>>1;
	if(mid+1<=l) return findsum(rc,l,r);
	else if(r<=mid) return findsum(lc,l,r);
	else return findsum(lc,l,mid)+findsum(rc,mid+1,r);
}
void dfs(int l,int r,int L,int R)
{
	if(L>R) return;
	if(l==r)
	{
		for(int i=L;i<=R;i++)
			if(b[i].op==2) ans[b[i].id]=l;
		return;
	}
	int mid=(l+r)>>1,t1=0,t2=0;
	for(int i=L;i<=R;i++)
		if(b[i].op==1)
		{
			if(b[i].z<=mid) d1[++t1]=b[i]; else d2[++t2]=b[i],change(1,b[i].x,b[i].y,1);
		}
		else
		{
			LL op=findsum(1,b[i].x,b[i].y);
			if(b[i].z<=op) d2[++t2]=b[i]; else b[i].z-=op,d1[++t1]=b[i];
		}
	for(int i=1;i<=t2;i++)
		if(d2[i].op==1) change(1,d2[i].x,d2[i].y,-1);
	for(int i=1;i<=t1;i++)
		b[L+i-1]=d1[i];
	for(int i=1;i<=t2;i++)
		b[L+t1+i-1]=d2[i];
	dfs(l,mid,L,L+t1-1);
	dfs(mid+1,r,L+t1-1+1,R);
}
int main()
{
	int t,x,y,cnt=0;
	LL z;
	scanf("%d %d",&n,&m);
	build(1,n);
	for(int i=1;i<=m;i++)
	{
		scanf("%d %d %d %lld",&t,&x,&y,&z);
		b[i]=(node1){t,t==2?++cnt:0,x,y,z};
	}
	dfs(-n,n,1,m);
	for(int i=1;i<=cnt;i++)
		printf("%d\n",ans[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值