省选专练之数据结构POI2014KUR-Couriers

主席树模板题

#include<bits/stdc++.h>
using namespace std;
const int N=4e5+10;
inline void read(int &x){
	x=0;
	char ch=getchar();
	int f=1;
	while(ch<'0'||ch>'9'){
		if(ch=='-'){
			f=-1;
		}
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();
	}
	x*=f;
}
int root[N]={};
int lson[N*30]={};
int rson[N*30]={};
int sum[N*30]={};
int cnt=0;
int n,m;
void update(int x,int &y,int l,int r,int val){
	y=++cnt;
	lson[y]=lson[x];
	rson[y]=rson[x];
	sum[y]=sum[x]+1;
	if(l==r){
		return; 
	}
	int mid=(l+r)/2;
	if(val<=mid){
		update(lson[x],lson[y],l,mid,val);
	}
	else{
		update(rson[x],rson[y],mid+1,r,val);
	}
}
int query(int L,int R){
	int x=root[L-1];
	int y=root[R];
	int l=1;
	int r=n;
	int Goal=(R-L+1)/2;
	while(1){
		if(sum[y]-sum[x]<Goal)return 0;
		if(l==r)break;
		int mid=(l+r)/2;
		if(sum[lson[y]]-sum[lson[x]]>Goal)r=mid,x=lson[x],y=lson[y];
		else{
			if(sum[rson[y]]-sum[rson[x]]>Goal)l=mid+1,x=rson[x],y=rson[y];
			else return 0;
		}
	}
	return l;
}
int main(){
	read(n);
	read(m);
	for(int i=1;i<=n;i++){
		int x;
		read(x);
		update(root[i-1],root[i],1,n,x);
	}
	while(m--){
		int l,r;
		read(l);
		read(r);
		cout<<query(l,r)<<'\n';
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值