You are given a tree with n nodes and e edges. Each node has a value. Then you are given Q queries. In each query, you are given a node number, and you need to return the XOR of all nodes in the subtree rooted at that node (including the node itself).
Show Answer
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
vector<int> adj[MAXN];
int subXor[MAXN];
void dfs(int u, int p) {
subXor[u] = u;
for (int v : adj[u]) {
if (v == p) continue;
dfs(v, u);
subXor[u] ^= subXor[v];
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, e;
cin >> n >> e;
while(e--) {
int u, v; cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, -1);
int Q; cin >> Q;
while (Q--) {
int node; cin >> node;
cout << subXor[node] << "\n";
}
}