让我们异或吧 DFS + 位运算技巧

题意

中文题意就不需要分析了吧

分析

我在洛谷上面搜的是LCA的标签,但是这道题跟LCA好像关系不太大?
首先因为有n - 1条边,首先我们可以确定这是一条树,然后我们去求异或值的时候,可以先求出点到跟节点的异或值,然后把待求的两点跟根节点之间的异或值异或一下就好了,因为重复的部分会进行抵消

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 100010;
int num[N];
int h[N],ne[N * 2],e[N * 2],w[N * 2],idx;
int f[N][21];
int d[N];
int n,m;

void add(int a,int b,int c){
    
    
    ne[idx] = h[a],e[idx] = b,w[idx] = c,h[a] = idx++;
}

void dfs(int u,int fa,int res){
    
    
    num[u] = res;
    for(int i = h[u];~i;i = ne[i]){
    
    
        int j = e[i];
        if(j == fa) continue;
        dfs(j,u,res ^ w[i]);
    }
}

int main(){
    
    
    scanf("%d",&n);
    memset(h,-1,sizeof h);
    for(int i = 0;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,1,0);
    scanf("%d",&m);
    while(m--){
    
    
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",num[x] ^ num[y]);
    }
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/110792228