显示代码纯文本
#include<bits/stdc++.h>
#define bianli for(int i=head[x];i;i=a[i].next)
#define QWQ cout<<"qwq";
#define me(qw) memset(qw,0x3f,sizeof(qw));
using namespace std;
const int maxn=1e5+5;
vector<int>v[maxn];
int tot,head[maxn];
struct road{int to,next,v;}a[maxn*2];
void add(int x,int y){
a[++tot].to=y;a[tot].next=head[x];head[x]=tot;}
int dep[maxn],cmt,top[maxn],s[maxn],dfn[maxn],_dfn[maxn],f[maxn],size[maxn],wson[maxn];
void dfs1(int x,int fa){
f[x]=fa;size[x]=1;dep[x]=dep[fa]+1;
bianli{
int to=a[i].to;
if(to==fa)continue;
dfs1(to,x);
size[x]+=size[to];
if(size[to]>size[wson[x]])wson[x]=to;}}
void dfs2(int x,int topf){
top[x]=topf;dfn[x]=++cmt;_dfn[cmt]=x;
if(wson[x]) dfs2(wson[x],topf);
bianli{
int to=a[i].to;
if(to==f[x]||to==wson[x])continue;
dfs2(to,to);}}
int ask(int x,int y,int z){
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]])swap(x,y);
if(upper_bound(v[z].begin(),v[z].end(),dfn[x])-lower_bound(v[z].begin(),v[z].end(),dfn[top[x]]))
return 1;
x=f[top[x]];}
if(dep[x]<dep[y])swap(x,y);
if(upper_bound(v[z].begin(),v[z].end(),dfn[x])-lower_bound(v[z].begin(),v[z].end(),dfn[y]))
return 1;
else return 0;}
int main(){
freopen("_milkvisits.in","r",stdin);
freopen("_milkvisits.out","w",stdout);
int n,m,q,w,e;
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>s[i];
for(int i=1;i<n;i++){cin>>q>>w;add(q,w);add(w,q);}
dfs1(1,0);dfs2(1,0);
for(int i=1;i<=n;i++)v[s[_dfn[i]]].push_back(i);
for(int i=1;i<=m;i++){
cin>>q>>w>>e;
cout<<ask(q,w,e);}
return 0;
}