让我们异或吧

洛谷P2420 让我们异或吧

bfs求根节点到每个点的路径异或值,因为a^c^b^c=a^b,所以输出d[x]^d[y]即可。

#include<bits/stdc++.h>
#define M 100010
#define mi 21
using namespace std;

int n,m,d[100100];
bool went[100010];

void in(int &x)
{
    char c=getchar();x=0;
    while(c<'0'||c>'9')c=getchar();
    while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
}
struct node
{
    int n,v;
    node *next;
}*e[M];

void push(int x,int y,int z)
{
    node *p;
    p=new node();
    p->n=y;
    p->v=z;
    if(e[x]==NULL)
     e[x]=p;
    else
    {
        p->next=e[x]->next;
        e[x]->next=p;
    }
}

queue<int>q;

void out(int x)
{
    if(x>9) out(x/10);
    putchar(x%10+'0');
}


void bfs(int x)
{
    q.push(x);
    node *p;
    d[x]=e[q.front()]->v;
    while(!q.empty())
    {
        p=e[q.front()];
        went[q.front()]=true;
        while(p!=NULL)
        {
            if(!went[p->n])
            {
              d[p->n]=d[q.front()]^p->v; 
              q.push(p->n);
            }
            p=p->next;
        }
        q.pop();
    }
}

int main()
{
   in(n);
   int x,y,z;
   for(int i=1;i<n;i++)
     {
         in(x),in(y),in(z);
         push(x,y,z);
         push(y,x,z);
     }
    in(m);
    bfs(1);
    for(int i=1;i<=m;i++)
    {
        in(x),in(y);
        out(d[x]^d[y]);
        putchar('
');
    }
   return 0;
}
原文地址:https://www.cnblogs.com/war1111/p/7365526.html