luogu_2420【题解】

  原本一看异或想弃疗。但是看完大佬题解之后发现了新大陆。

  a^a=0。

  这样就可以一遍dfs求出所有点到根路径的异或,然后再O(1)求xor[x]^xor[y]。

  代码如下。

#include<bits/stdc++.h>
using namespace std;
const int maxn=100000+10;
int n,m,tot,head[maxn],xo[maxn];
struct node{
    int nxt,to,dis;
}edge[maxn<<1];
inline void add(int from,int to,int dis){
    edge[++tot].nxt=head[from],edge[tot].to=to;
    head[from]=tot,edge[tot].dis=dis;
}
void dfs(int x,int fa,int k){
    xo[x]=k;
    for(int i=head[x];i;i=edge[i].nxt){
        int v=edge[i].to;if(v==fa) continue;
        else{
            dfs(v,x,k^edge[i].dis);
        }
    }
    return;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n-1;i++){
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        add(x,y,z);add(y,x,z);
    }
    dfs(1,0,0);
    cin>>m;
    while(m--){
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",xo[x]^xo[y]);
    }
    return 0;
}

 

posted @ 2019-04-23 21:58  ChrisKKK  阅读(140)  评论(0编辑  收藏  举报