luogu P4137 Rmq Problem / mex(可持久化线段树)

一开始想的是莫队,然后维护几个bitset,然后瞎搞。脑子里想了想实现,发现并不好写。
还是主席树好写。我们维护一个权值的线段树,记录每一个权值的最后一次出现的位置下标。我们查询的时候要在前(r)颗线段树中找到第一个出现的位置下标小于(l)的数,在线段树上二分就行了。
这个想法还是非常巧妙的。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=201000;
int n,m,b[N*2],a[N],root[N],mn[N*40],tot,num,cnt,ch[N*40][2];
void build(int l,int r,int &now){
	now=++num;
	if(l==r)return;
	int mid=(l+r)>>1;
	build(l,mid,ch[now][0]);
	build(mid+1,r,ch[now][1]);
}
void add(int l,int r,int x,int w,int pre,int &now){
	now=++num;
	ch[now][0]=ch[pre][0];
	ch[now][1]=ch[pre][1];
	if(l==r){
		mn[now]=w;
		return;
	}
	int mid=(l+r)>>1;
	if(x>mid)add(mid+1,r,x,w,ch[pre][1],ch[now][1]);
	else add(l,mid,x,w,ch[pre][0],ch[now][0]);
	mn[now]=min(mn[ch[now][0]],mn[ch[now][1]]);
}
int check(int l,int r,int x,int now){
	while(l<r){
		int mid=(l+r)>>1;
		int tmp=mn[ch[now][0]];
		if(tmp<x)now=ch[now][0],r=mid;
		else l=mid+1,now=ch[now][1];
	}
	return b[l];
}
int read(){
	int sum=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
	return sum*f;
}
int main(){
	n=read(),m=read();
	b[++cnt]=0;
	for(int i=1;i<=n;i++)a[i]=read(),b[++cnt]=a[i],b[++cnt]=a[i]+1;
	sort(b+1,b+1+cnt);
	tot=unique(b+1,b+1+cnt)-b-1;
//	build(1,tot,root[0]);
	for(int i=1;i<=n;i++)add(1,tot,lower_bound(b+1,b+1+tot,a[i])-b,i,root[i-1],root[i]);
	while(m--){
		int l=read(),r=read();
		printf("%d
",check(1,tot,l,root[r]));
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Xu-daxia/p/10134016.html