Graph Theory Essay

Let it XOR

Although this problem can be done with the $ LCA $, but in order to practice graph theory, I chose the method before using the chain traverses the star

First prepare a few things

1 a ^ 0 = a
2 a ^ a = 0

Then you'll notice, if the request is regarded each graph traversal once, then only $ 40pts $, so I use $ xors $ array to store

It can be shown regardless of which node is taken as a starting point, $ xors [u] $ and $ xors [v] $ XORed is constant

Code

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int n, m, cnt = 0, ans, book[100005];
 5 int head[200005], xors[100005];
 6 
 7 struct Edge {
 8     int to;
 9     int val;
10     int nxt;
11 };
12 
13 Edge edge[200005];
14 
15 void add(int from, int to, int value) {
16     ++cnt;
17     edge[cnt].to = to;
18     edge[cnt].nxt = head[from];
19     edge[cnt].val = value;
20     head[from] = cnt;
21 }
22 
23 void get(int now, int last) {
24     for(int i = head[now]; i != -1; i = edge[i].nxt) {
25         if(edge[i].to != last) {
26             xors[edge[i].to] = xors[now] ^ edge[i].val;
27             get(edge[i].to, now);
28         }
29     }
30     return ;
31 }
32 
33 void solve() {
34     int u, v, w;
35     memset(head, -1, sizeof(head));
36     scanf("%d", &n);
37     for(int i = 1; i < n; i++) {
38         scanf("%d%d%d", &u, &v, &w);
39         add(u, v, w);
40         add(v, u, w);
41     }
42     get(1, 0);
43     scanf("%d", &m);
44     for(int i = 1; i <= m; i++) {
45         scanf("%d%d", &u, &v);
46         printf("%d\n", xors[u]^xors[v]);
47     }
48 }
49 
50 int main() {
51     solve();
52     return 0;
53 }
Let it XOR

 

Guess you like

Origin www.cnblogs.com/CsyzFraction/p/11260666.html