题解
树上只有两种颜色,我们把每种颜色的连通块记录下来,只有当路径两端的点属于同一连通块且颜色与朋友喜欢的不同时输出0
code
#include<bits/stdc++.h>
using namespace std;
char s[100005];
int fa[100005];
int finds(int now){return fa[now]==now?now:fa[now]=finds(fa[now]);}
vector<int> G[100005];
void dfs(int now,int pre)
{
for(auto next:G[now])
{
if(pre==next) continue;
dfs(next,now);
if(s[next]==s[now]) fa[finds(next)]=now;
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) fa[i]=i;
cin>>(s+1);
for(int i=1;i<n;i++)
{
int x,y;
cin>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1,1);
string ans;
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
char a;
cin>>a;
if(finds(x)==finds(y)&&s[finds(x)]!=a) ans+='0';
else ans+='1';
}
cout<<ans;
return 0;
}
标签:fa,int,Visits,finds,P5836,dfs,now,next,Milk
From: https://www.cnblogs.com/pure4knowledge/p/18111367