感觉数组开的够大了,又开大了10倍还是re
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
#define int long long
struct node
{
/* data */
int v,nt;
}edge[1000010];
struct yzh
{
/* data */
int l,r,cnt;
}tre[50000010];
int n,m,h[1000010],head[1000010],tot,hi[1000010],a[1000010],fat[1000010][22],dep[1000010],las,root[1000010];
int b[1000010],len,tot2,nrt;
void add(int u,int v){
edge[++tot]={v,head[u]};head[u]=tot;
edge[++tot]={u,head[v]};head[v]=tot;
}
void high(int x,int fa){
fat[x][0]=fa;
dep[x]=dep[fa]+1;
for(int i=1;i<=18;++i){
fat[x][i]=fat[fat[x][i-1]][i-1];
// if(x==2) cout<<x<<";;"<<fat[3][0]<<endl;
}
for(int i=head[x];i;i=edge[i].nt){
int v=edge[i].v;
if(v==fa) continue;
high(v,x);
// if(v==3) cout<<x<<";;"<<fat[3][0]<<endl;
}
}
int lca(int u,int v){
if(dep[u]<dep[v]) swap(u,v);
int pot=18;
while(dep[u]>dep[v]&&pot>=0){
if(dep[fat[u][pot]]>=dep[v]){
u=fat[u][pot];
}
pot--;
}
// u=fat[u][0];
// cout<<"1."<<u<<" "<<fat[u][0]<<endl;
if(u==v){
return u;
}
pot=18;
while(u!=v&&pot>=0){
if(fat[u][pot]!=fat[v][pot]){
// cout<<pot<<endl;
u=fat[u][pot];v=fat[v][pot];
}
pot--;
}
// cout<<"2."<<v<<endl;
u=fat[u][0];
return u;
}
int update(int pre,int l,int r,int xl){
if(l>r) return 0;
int rot=++tot2;
if(l==r&&xl==l){
tre[rot]=tre[pre];
tre[rot].cnt++;
return rot;
}
tre[rot]=tre[pre];
int mid=(l+r)>>1;
if(xl<=mid){
tre[rot].l=update(tre[pre].l,l,mid,xl);
}else{
tre[rot].r=update(tre[pre].r,mid+1,r,xl);
}
tre[rot].cnt=tre[tre[rot].l].cnt+tre[tre[rot].r].cnt;
return rot;
}
int query(int prt,int pre1,int pre2,int l,int r,int k){
// cout<<l<<" "<<r<<endl;
// if(l>r) return 0;
// int rot=++tot2;
if(l==r){
return l;
}
int mid=(l+r)>>1;
int sum=tre[tre[pre2].l].cnt+tre[tre[pre1].l].cnt-2*tre[prt].cnt;
// cout<<"?"<<sum<<endl;
if(k<=sum) return query(prt,tre[pre1].l,tre[pre2].l,l,mid,k);
else return query(prt,tre[pre1].r,tre[pre2].r,mid+1,r,k-sum);
}
void built(int x,int fa){
root[x]=update(root[fa],1,len,a[x]);
// if(x==2) cout<<"lsl"<<root[x]<<endl;
for(int i=head[x];i;i=edge[i].nt){
int v=edge[i].v;
if(v==fa) continue;
built(v,x);
}
}
signed main(){
scanf("%lld%lld",&n,&m);
for(int i=1;i<=n;++i){
scanf("%lld",&a[i]);
b[i]=a[i];
}
sort(b+1,b+n+1);
len=unique(b+1,b+n+1)-(b+1);
for(int i=1;i<=n;++i){
a[i]=lower_bound(b+1,b+len+1,a[i])-b;
// cout<<a[i]<<endl;
}
for(int i=1;i<n;++i){
int u,v;
scanf("%lld%lld",&u,&v);
add(u,v);
}
high(1,0);
// cout<<fat[3][0]<<endl;
built(1,0);
for(int i=1;i<=m;++i){
int u,v,k;
scanf("%lld%lld%lld",&u,&v,&k);
int lcat=lca(u^las,v);
// cout<<";;"<<(u^las)<<" "<<v<<endl;
// cout<<"::"<<lcat<<endl;
// int xtt=tot2;
// nrt=bl(root[fat[lcat][0]],root[u^las],root[v],1,len);
// tot2=xtt;
int idt=query(root[fat[lcat][0]],root[u^las],root[v],1,len,k);
// cout<<idt<<endl;
// if(idt>1e5) continue;
las=b[idt];
// cout<<"??"<<tre[nrt].cnt<<endl;
// cout<<query(nrt,1,len,k)<<":";
printf("%lld\n",las);
}
return 0;
}