提交时间:2022-07-13 11:52:03

运行 ID: 51548

#include<cstdio> #include<iostream> #include<bitset> using namespace std; const int N=1e5+5; int n,m,head[N],tot; bitset<N>s[N],a,b; struct node { int nex,v,w; }edge[N<<1]; void Add(int x,int y,int z) { edge[++tot]=(node){head[x],y,z};head[x]=tot; edge[++tot]=(node){head[y],x,z};head[y]=tot; } void dfs(int x,int fa) { for(int i=head[x];i;i=edge[i].nex) { int y=edge[i].v,z=edge[i].w; if(y==fa) continue; s[y]=s[x];s[y][z]=s[x][z]^1; dfs(y,x); } } bool check(int l,int r) { b=a>>(r+1); int cnt=b.count(); b=a>>l; return b.count()==cnt; } int main() { int x,y,z,R; scanf("%d",&n); for(int i=1;i<n;i++) scanf("%d%d%d",&x,&y,&z),Add(x,y,z); dfs(1,0); scanf("%d",&m); while(m--) { scanf("%d%d%d",&x,&y,&R); a=s[x]^s[y]; int l=1,r=R,mid,ans=R+1; while(l<=r) { int mid=(l+r)>>1; if(check(mid,R)) ans=mid,r=mid-1; else l=mid+1; } printf("%d\n",R-ans+1); } return 0; }