洛谷传送门
题目描述
异或是一种神奇的运算,大部分人把它总结成不进位加法.
在生活中…xor运算也很常见。比如,对于一个问题的回答,是为1,否为0.那么:
(A是否是男生 )xor( B是否是男生)=A和B是否能够成为情侣
好了,现在我们来制造和处理一些复杂的情况。比如我们将给出一颗树,它很高兴自己有N个结点。树的每条边上有一个权值。我们要进行M次询问,对于每次询问,我们想知道某两点之间的路径上所有边权的异或值。
输入输出格式
输入格式:
输入文件第一行包含一个整数N,表示这颗开心的树拥有的结点数,以下有N-1行,描述这些边,每行有3个数,u,v,w,表示u和v之间有一条权值为w的边。接下来一行有一个整数M,表示询问数。之后的M行,每行两个数u,v,表示询问这两个点之间的路径上的权值异或值。
输出格式:
输出M行,每行一个整数,表示异或值
输入输出样例
输入样例#1:
5
1 4 9644
2 5 15004
3 1 14635
5 3 9684
3
2 4
5 4
1 1
输出样例#1:
975
14675
0
说明
对于40%的数据,有1 ≤ N,M ≤ 3000;
对于100%的数据,有1 ≤ N ,M≤ 100000。
解题分析
异或的妙妙性质使得异或两次的部分会抵消为0, 所以我们随便找一个点作为树根, DFS一次算出每个点到根节点的异或和, 然后 O(1) O ( 1 ) 查询就好了。
代码如下:
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#define R register
#define IN inline
#define gc getchar()
#define W while
#define MX 100005
template <class T>
IN void in (T &x)
{
x = 0; R char c = gc;
W (!isdigit(c)) c = gc;
W (isdigit(c))
{x = (x << 1) + (x << 3) + c - 48, c = gc;}
}
int head[MX], ans[MX], cnt, dot, q;
struct Edge
{
int to, val, nex;
}edge[MX << 1];
IN void addedge(const int &from, const int &to, const int &len)
{
edge[++cnt] = (Edge){to, len, head[from]};
head[from] = cnt;
}
void DFS(const int &now, const int &pre)
{
for (R int i = head[now]; i; i = edge[i].nex)
{
if(edge[i].to == pre) continue;
ans[edge[i].to] = ans[now] ^ edge[i].val;
DFS(edge[i].to);
}
}
int main(void)
{
int a, b, c;
in(dot);
for (R int i = 1; i < dot; ++i)
{
in(a), in(b), in(c);
addedge(a, b, c);
addedge(b, a, c);
}
DFS(1, 0);
in(q);
W (q--)
{
in(a), in(b);
printf("%d\n", ans[a] ^ ans[b]);
}
}