1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include<bits/stdc++.h> #define maxn 100007 using namespace std; int n,m,fa[maxn],head[maxn],son[maxn],sz[maxn],ol; int T[maxn],tot,a[maxn],top[maxn],dep[maxn],b[maxn]; int lastans,cent; struct node{ int next,to; }edge[maxn<<1]; struct ML{ int l,r,sum; };
template<typename type_of_scan> inline void scan(type_of_scan &x){ type_of_scan f=1;x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} x*=f; } template<typename Tops,typename... tops> inline void scan(Tops &x,tops&... X){ scan(x),scan(X...); } template<typename type_of_print> inline void print(type_of_print x){ if(x<0) putchar('-'),x=-x; if(x>9) print(x/10); putchar(x%10+'0'); }
inline void add(int u,int v){ edge[++cent]=(node){head[u],v};head[u]=cent; edge[++cent]=(node){head[v],u};head[v]=cent; }
struct tree{ ML tr[maxn*20]; void add(int &rt,int pre,int l,int r,int x){ rt=++tot; tr[rt]=tr[pre],tr[rt].sum++; if(l==r) return ; int mid=l+r>>1; if(x<=mid) add(tr[rt].l,tr[pre].l,l,mid,x); else add(tr[rt].r,tr[pre].r,mid+1,r,x); } int query(int u,int v,int lca,int flca,int l,int r,int k){ if(l==r) return l; int mid=l+r>>1; int x=tr[tr[u].l].sum+tr[tr[v].l].sum-tr[tr[lca].l].sum-tr[tr[flca].l].sum; if(k<=x) return query(tr[u].l,tr[v].l,tr[lca].l,tr[flca].l,l,mid,k); else return query(tr[u].r,tr[v].r,tr[lca].r,tr[flca].r,mid+1,r,k-x); } }t;
void dfs1(int x){ sz[x]=1;t.add(T[x],T[fa[x]],1,ol,a[x]); for(int i=head[x];i;i=edge[i].next){ int y=edge[i].to; if(y==fa[x]) continue; fa[y]=x;dep[y]=dep[x]+1; dfs1(y);sz[x]+=sz[y]; if(sz[son[x]]<sz[y]) son[x]=y; } }
void dfs2(int x,int tp){ top[x]=tp; if(!son[x]) return ; dfs2(son[x],tp); for(int i=head[x];i;i=edge[i].next){ int y=edge[i].to; if(y==fa[x]||y==son[x]) continue; dfs2(y,y); } }
int get_lca(int x,int y){ while(top[x]!=top[y]){ if(dep[top[x]]<dep[top[y]]) swap(x,y); x=fa[top[x]]; } return dep[x]<dep[y]?x:y; }
int main(){ scan(n,m); for(int i=1;i<=n;i++) scan(a[i]),b[i]=a[i]; sort(b+1,b+1+n); ol=unique(b+1,b+1+n)-b-1; for(int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+1+ol,a[i])-b; for(int i=1,u,v;i<=n-1;i++) scan(u,v),add(u,v); dfs1(1),dfs2(1,1); for(int i=1,u,v,k;i<=m;i++){ scan(u,v,k);u^=lastans; int lca=get_lca(u,v); int pos=t.query(T[u],T[v],T[lca],T[fa[lca]],1,ol,k); printf("%d\n",b[pos]);lastans=b[pos]; } }
|