洛谷2420

题目地址

题解

求出每一个点到根的$xor$路径,然后直接$O(1)$回答询问。
答案就是$val[u]\quad xor\quad val[v]$,因为$val[lca]$被消去了。
这真的是经典问题?我怀疑你就是在水

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cctype>
#define INF 2000000000
using namespace std;
typedef long long ll;
struct Edge{
int v,cost,_next;
};
Edge edge[200006];
int cnt=0,at[100005]={0},n,val[100005]={0};
void addedge(int _u,int _v,int _cost){
edge[++cnt].v=_v,
edge[cnt].cost=_cost,
edge[cnt]._next=at[_u],
at[_u]=cnt;
}
int read(){
int f=1,x=0;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-f;c=getchar();}
while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
return f*x;
}
void dfs(int x,int fa){
for(int i=at[x];i;i=edge[i]._next)
if(edge[i].v!=fa)
val[edge[i].v]=val[x]^edge[i].cost,
dfs(edge[i].v,x);
}
void init(){
n=read();
int u,v,c;
for(int i=1;i<n;i++)
u=read(),v=read(),c=read(),
addedge(u,v,c),addedge(v,u,c);
dfs(1,0);
}
void solve(){
int m=read(),u,v;
while(m--)
u=read(),v=read(),
printf("%d\n",val[u]^val[v]);
}
int main(){
init();
solve();
return 0;
}