样例过了,交上去6WA,剩下的TLE了
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
struct Tree
{
int father;
int heavyson=0;
int deep;
int size=1;
int top;
int id;
int point;
}tree[maxn];
int n,m,q,top[maxn],head[maxn],to[2*maxn],nxt[2*maxn],cnt,cnt2,team[maxn],nid[maxn];
void add(int x,int y)
{
to[++cnt]=y;
nxt[cnt]=head[x];
head[x]=cnt;
}
void dfs1(int x,int f)
{
tree[x].deep=tree[f].deep+1;
tree[x].father=f;
int j=head[x];
int maxsize=-1;
for(int j=head[x];j;j=nxt[j])
{
if(to[j]==f)
{
j=nxt[j];
continue;
}
dfs1(to[j],x);
tree[x].size+=tree[to[j]].size;
if(tree[to[j]].size>maxsize)
{
maxsize=tree[to[j]].size;
tree[x].heavyson=to[j];
}
}
return;
}
int id=0;
void dfs2(int x,int top)
{
id++;
tree[x].id=id;
nid[id]=x;
tree[x].top=top;
if(tree[x].heavyson==0) return;
dfs2(tree[x].heavyson,top);
for(int j=head[x];j;j=nxt[j])
{
if(to[j]==tree[x].heavyson||to[j]==tree[x].father)
{
continue;
}
dfs2(to[j],to[j]);
}
return;
}
vector<int>cow[maxn];
int LCA(int x,int y,int p)
{
while(tree[x].top!=tree[y].top)
{
if(tree[tree[x].top].deep<tree[tree[y].top].deep) swap(x,y);
vector<int>::iterator it=lower_bound(cow[p].begin(),cow[p].end(),tree[tree[x].top].id);
if(it!=cow[p].end()&&*it<=tree[x].id) return 1;
x=tree[tree[x].top].father;
}
if(tree[x].deep<tree[y].deep) swap(x,y);
vector<int>::iterator it=lower_bound(cow[p].begin(),cow[p].end(),tree[y].id);
if(it!=cow[p].end()&&*it<=tree[x].id) return 1;
return 0;
}
int read()
{
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=(x<<3)+(x<<1)+c-'0';
c=getchar();
}
return x*f;
}
int main()
{
int tmp,tmp1,tmp2;
n=read(),m=read();
for(int i=1;i<=n;i++)
{
team[i]=read();
}
for(int i=1;i<n;i++)
{
tmp=read(),tmp1=read();
add(tmp,tmp1);
add(tmp1,tmp);
}
dfs1(1,0);
dfs2(1,0);
for(int i=1;i<=id;i++)
{
cow[team[nid[i]]].push_back(i);
}
while(m--)
{
tmp=read(),tmp1=read(),tmp2=read();
printf("%d",LCA(tmp,tmp1,tmp2));
}
}