[ZJOI2013]K大数查询

题面

题解

整体二分

区间查询可以二分,把所有的询问放在一起,用线段树区间查询即可。

代码

#include<bits/stdc++.h>
#define RG register
using namespace std;

inline int read()
{
	int data=0, w=1;
	char ch=getchar();
	while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
	if(ch=='-') w=-1, ch=getchar();
	while(ch>='0'&&ch<='9') data=(data<<3)+(data<<1)+(ch^48), ch=getchar();
	return data*w;
}

const int maxn(50010);
struct node
{
	bool clr; int lazy; long long sum;
	inline void clear() { clr=lazy=sum=0; }
}tree[maxn << 2];

int n, m, ans[maxn];
#define son(i) ((root<<1)|i)
inline void pushdown(int root, int l, int r)
{
	if(tree[root].clr)
	{
		tree[son(0)].clear(); tree[son(1)].clear();
		tree[son(0)].clr=tree[son(1)].clr=1; tree[root].clr=0;
	}
	int mid(l+r>>1);
	tree[son(0)].sum+=tree[root].lazy*(mid-l+1);
	tree[son(1)].sum+=tree[root].lazy*(r-mid);
	tree[son(0)].lazy+=tree[root].lazy;	
	tree[son(1)].lazy+=tree[root].lazy;
	tree[root].lazy=0;
}

void update(int ql, int qr, int root=1, int l=1, int r=n)
{
	if(r<ql || qr<l) return;
	if(ql<=l && r<=qr)
	{
		tree[root].sum+=r-l+1;
		tree[root].lazy++; return;
	}
	pushdown(root, l, r);
	int mid(l+r>>1);
	update(ql, qr, son(0), l, mid);
	update(ql, qr, son(1), mid+1, r);
	tree[root].sum=tree[son(0)].sum+tree[son(1)].sum;
}

long long query(int ql, int qr, int root=1, int l=1, int r=n)
{
	if(r<ql || qr<l) return 0;
	if(ql<=l && r<=qr) return tree[root].sum;
	pushdown(root, l, r); int mid(l+r>>1);
	return query(ql, qr, son(0), l, mid)+query(ql, qr, son(1), mid+1, r);
}

struct question { int opt, l, r, c, id; } p[maxn], p1[maxn], p2[maxn];
void divde(int ql, int qr, int l, int r)
{
	if(ql>qr) return;
	if(l==r) { for(RG int i=ql;i<=qr;i++) ans[p[i].id]=l; return; }
	int mid=(l+r)>>1, t1=0, t2=0;
	for(RG int i=ql;i<=qr;i++)
	{
		if(p[i].opt^1)
		{
			long long q=query(p[i].l, p[i].r);
			if(q>=p[i].c) p2[++t2]=p[i];
			else p[i].c-=q, p1[++t1]=p[i];
		}
		else
		{
			if(p[i].c<=mid) p1[++t1]=p[i];
			else { p2[++t2]=p[i]; update(p[i].l, p[i].r); }
		}
	}
	for(RG int i=1;i<=t1;i++) p[ql+i-1]=p1[i];
	for(RG int i=1;i<=t2;i++) p[ql+t1+i-1]=p2[i];
	tree[1].clear(); tree[1].clr=1;
	divde(ql, ql+t1-1, l, mid); divde(ql+t1, qr, mid+1, r);
}

int main()
{
	n=read(); m=read();
	int tot=0;
	for(RG int i=1;i<=m;i++)
	{
		p[i]=(question){read(), read(), read(), read(), 0};
		if(p[i].opt^1) p[i].id=++tot;
	}
	divde(1, m, -n, n);
	for(RG int i=1;i<=tot;i++) printf("%d\n", ans[i]);
	return 0;
}
posted @ 2018-10-16 21:08  xgzc  阅读(478)  评论(0编辑  收藏  举报