hdu Dylans loves tree [LCA] (树链剖分)

时间:2021-11-06 08:14:06

Dylans loves tree

hdu Dylans loves tree [LCA] (树链剖分)hdu Dylans loves tree [LCA] (树链剖分)
view code#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#define REP(i, n) for(int i = 0; i < (n); ++i)
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
using namespace std;
typedef vector<int > VI;
typedef pair<int, int > PII;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 100010;
int _, cas=1, n, Q, m, val[N], seg[N << 2]; struct Edge {
int u, v, next;
Edge() {}
Edge(int u, int v, int next):u(u), v(v), next(next) {}
}e[N << 1];
int head[N], ecnt; void add(int u, int v) {
e[ecnt] = Edge(u, v, head[u]);
head[u] = ecnt++;
} int dep[N], fa[N], sz[N], top[N], id[N], fid[N], gid, son[N];
void dfs(int u, int f, int d) {
fa[u] = f, sz[u] = 1, dep[u] = d, son[u] = 0;
for(int i = head[u]; ~i; i = e[i].next) {
int v = e[i].v;
if(v == f) continue;
dfs(v, u, d + 1);
sz[u] += sz[v];
if(sz[ son[u] ] < sz[v]) son[u] = v;
}
} void getpos(int u, int f) {
id[u] = ++gid;
fid[gid] = u;
top[u] = f;
if(!son[u]) return ;
getpos(son[u], f);
for(int i = head[u]; ~i; i = e[i].next) {
int v = e[i].v;
if(v == son[u] || v == fa[u]) continue;
getpos(v, v);
}
} void pushUp(int rt) {
seg[rt] = seg[rt << 1] ^ seg[rt << 1 | 1];
} void build(int l, int r, int rt) {
if(l == r) {
seg[rt] = val[ fid[l] ];
return ;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
pushUp(rt);
} void update(int p, int c, int l, int r, int rt) {
if(l == r) {
seg[rt] = c;
return ;
}
int m = (l + r) >> 1;
if(p <= m) update(p, c, lson);
else update(p, c, rson);
pushUp(rt);
} int query(int L, int R, int l, int r, int rt) {
if(L <= l && R >= r) return seg[rt];
int m = (l + r) >> 1, ans = 0;
if(L <= m) ans ^= query(L, R, lson);
if(R > m) ans ^= query(L, R, rson);
return ans;
} int lca(int u, int v) {
int fu = top[u], fv = top[v], ans = 0, dis = 0;
while(fu != fv) {
if(dep[fu] < dep[fv]) {
swap(fu, fv), swap(u, v);
}
ans ^= query(id[fu], id[u], 1, n, 1);
dis += id[u] - id[fu] + 1;
u = fa[fu];
fu = top[u];
}
if(dep[u] < dep[v]) swap(u, v);
ans ^= query(id[v], id[u], 1, n, 1);
dis += id[u] - id[v] + 1;
return (dis & 1) ? ans : -1;
} void solve() {
scanf("%d%d", &n, &Q); ecnt = 0;
memset(head, -1, sizeof(head[0]) * sizeof(n +5));
int u, v;
REP(i, n - 1) {
scanf("%d%d", &u, &v);
add(u, v);
add(v, u);
}
FOR(i, 1, n) {
scanf("%d", &val[i]);
} sz[0] = 0;
gid = 0;
dfs(1, 1, 0);
getpos(1, 1);
build(1, n, 1); int flag;
while(Q--) {
scanf("%d%d%d", &flag, &u, &v);
if(flag) {
printf("%d\n", lca(u, v));
} else {
update(id[u], v, 1, n, 1);
}
}
} int main()
{
cin >> _;
while(_--) solve();
return 0;
}