P6098 [USACO19FEB] Cow Land G
可恶,上一个是线段树调试失败,利用树状数组做的,这一次看到单点修改区间查询,果断选着树状数组,结果wa了。
果然我还是太菜了
此题几乎是模板题,只要修改下线段树的向上传递即可,因为是单点修改,所以可以不用懒标记
注意这里求的是异或
点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n;
int a[N];
//树链
vector<int> g[N];
int dep[N], fa[N], sz[N], son[N];
void dfs1(int u,int father) {
dep[u] = dep[father] + 1;
fa[u] = father; sz[u] = 1;
for (int v : g[u]) {
if (v == father) continue;
dfs1(v, u);
sz[u] += sz[v];
if (sz[son[u]] < sz[v]) son[u] = v;
}
}
int top[N], cnt, id[N],nw[N];
void dfs2(int u, int t) {
top[u] = t; id[u] = ++cnt, nw[cnt] = a[u];
if (!son[u]) return;
dfs2(son[u], t);
for (int v : g[u]) {
if (v == fa[u] || v == son[u]) continue;
dfs2(v, v);
}
}
//线段树
#define lc k<<1
#define rc k<<1|1
struct tree {
int l, r;
int sum;
}t[N*4];
void pushup(int k) {
t[k].sum = t[lc].sum ^ t[rc].sum;//异或一下
}
void build(int k, int l, int r) {
t[k] = { l,r };
if (l == r) {
t[k].sum = nw[l];
return;
}
int mid = l + r >> 1;
build(lc, l, mid); build(rc, mid + 1, r);
pushup(k);
}
void modify(int k, int x,int z) {
if (t[k].l == x && t[k].r == x) {
t[k].sum = z;
return;
}
int mid = t[k].l + t[k].r >> 1;
if (x <= mid) modify(lc, x, z);
else modify(rc, x, z);
pushup(k);
}
int query(int k, int l, int r) {
if (t[k].l >= l && t[k].r <= r) return t[k].sum;
int mid = t[k].l + t[k].r >> 1;
int res = 0;
if (l <= mid) res ^= query(lc, l, r);
if (r > mid) res ^= query(rc, l, r);
return res;
}
int ask_path(int u, int v) {
int res = 0;
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(v, u);
res ^= query(1, id[top[u]], id[u]);
u = fa[top[u]];
}
if (dep[u] < dep[v]) swap(u, v);
res ^= query(1, id[v], id[u]);
return res;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int Q;
cin >> n>>Q;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs1(1, 0);
dfs2(1, 1);
build(1, 1, n);
while (Q--) {
int op, x, y;
cin >> op >> x >> y;
if (op == 1) {
modify(1, id[x], y);
}
else {
cout << ask_path(x, y) << '\n';
}
}
return 0;
}