原题:https://www.luogu.org/problemnew/show/P3302
题解:维护一种数据结构,在一棵树上就两点路径上的第k小,合并两颗树。首先考虑路径上的第k小,很明显时主席树,但是是树上的,和数组类似只用复制他的父节点的信息就行了。查询时x-y之间的信息应该是:T[x]+T[y]-T[lca]-T[fa[lca]]正好是x->y路径上的信息(就像数组T[y]-T[x-1]一样)。然后就是静态区间第k小的问题。然后考虑合并,将节点数量少的往大的合并重新更新一下小的信息。
然后要注意数组要开足够大,因为我们update一直在新建节点。离散化!!!testdata是第几组测试数据,不要当成多组测试数据。
#include<bits/stdc++.h>
#define mid (l+r)/2
using namespace std;
const int N=8e4+10;
const int M=20;
struct E{int to,nxt;}data[N<<2];
char ch[10];
int cas,n,m,q,cnt,len,tot,ans;
int a[N],b[N],h[N],T[N],L[N*M*30],R[N*M*30],sum[N*M*30],sz[N],st[N][M],dep[N];
bool vis[N];
inline int rd(){
int x=0;int f=1;char s=getchar();
while(!isdigit(s)) f=(s=='-'?-1:f),s=getchar();
while(isdigit(s)) x=(x<<1)+(x<<3)+s-'0',s=getchar();
return x*f;
}
inline void init(){
memset(h,0,sizeof h);memset(sz,0,sizeof sz);
memset(vis,0,sizeof vis);memset(st,0,sizeof st);
ans=0;len=1;tot=0;dep[0]=0;
}
inline void ins(int x,int y){
data[++len].to=y;data[len].nxt=h[x];h[x]=len;
data[++len].to=x;data[len].nxt=h[y];h[y]=len;
}
inline int build(int l,int r){
int rt=++tot;
sum[rt]=0;
if(l<r){
L[rt]=build(l,mid);
R[rt]=build(mid+1,r);
}
return rt;
}
inline int update(int pre,int l,int r,int x){
int rt=++tot;
L[rt]=L[pre];R[rt]=R[pre];sum[rt]=sum[pre]+1;
if(l==r) return rt;
if(x<=mid) L[rt]= update(L[pre],l,mid,x);
else R[rt]= update(R[pre],mid+1,r,x);
return rt;
}
inline int getfa(int x){
for(int j=M-1;j>=0;j--) if(st[x][j]) x=st[x][j];
return x;
}
void dfs(int x,int fa,int rt){
st[x][0]=fa;
for(int j=1;j<M;j++)
st[x][j]=st[st[x][j-1]][j-1];
dep[x]=dep[fa]+1;
sz[rt]++;vis[x]=1;
T[x]=update(T[fa],1,cnt,b[x]);
for(int i=h[x];i;i=data[i].nxt){
int y=data[i].to;if(y==fa) continue;
dfs(y,x,rt);
}
}
inline int LCA(int x,int y){
if(dep[x]<dep[y]) swap(x,y);
for(int j=M-1;j>=0;j--)
if(dep[st[x][j]]>=dep[y]) x=st[x][j];
if(x==y) return y;
for(int j=M-1;j>=0;j--)
if(st[x][j]!=st[y][j]) x=st[x][j],y=st[y][j];
return st[x][0];
}
inline int query(int x,int y,int lca,int flca,int l,int r,int k){
if(l==r) return a[l];
int s=sum[L[x]]+sum[L[y]]-sum[L[lca]]-sum[L[flca]];
if(k<=s) return query(L[x],L[y],L[lca],L[flca],l,mid,k);
else return query(R[x],R[y],R[lca],R[flca],mid+1,r,k-s);
}
int main(){
// freopen("sdoi2013.in","r",stdin);
cas=rd();n=rd();m=rd();q=rd();
for(int i=1;i<=n;i++) b[i]=a[i]=rd();
//离散化
sort(a+1,a+n+1);cnt=unique(a+1,a+n+1)-(a+1);
for(int i=1;i<=n;i++) b[i]=lower_bound(a+1,a+cnt+1,b[i])-a;
for(int i=1,x,y;i<=m;i++){x=rd();y=rd();ins(x,y);}
//空树
T[0]=build(1,cnt);
for(int i=1;i<=n;i++)if(!vis[i]) dfs(i,0,i);
for(int i=1,x,y,k;i<=q;i++){
scanf("%s",ch);x=rd();y=rd();
x^=ans;y^=ans;
if(ch[0]=='Q'){
k=rd();k^=ans;int lca=LCA(x,y);
printf("%d\n",ans=query(T[x],T[y],T[lca],T[st[lca][0]],1,cnt,k));
}else {
int fx=getfa(x);
int fy=getfa(y);ins(x,y);
if(sz[fx]<sz[fy]) swap(x,y),swap(fx,fy);
dfs(y,x,fx);
}
}
return 0;
}