1 条题解
-
0
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; vector<pair<int, int>> G[N]; struct Edge { int x, y, c; } e[N]; struct tnode { int fa, dep, son, tot, tp, z; } t[N]; void dfs1(int x, int xfa) { t[x] = tnode{xfa, t[xfa].dep + 1, 0, 1, x, x}; for (auto i : G[x]) { int y = i.first; if (y != xfa) { dfs1(y, x); t[x].tot += t[y].tot; if (t[t[x].son].tot < t[y].tot) t[x].son = y; } } } int z = 0; void dfs2(int x, int tp) { t[x].z = ++z; t[x].tp = tp; if (t[x].son != 0) dfs2(t[x].son, tp); for (auto i : G[x]) { int y = i.first; if (y != t[x].son && y != t[x].fa) dfs2(y, y); } } struct trnode { int lc, rc, l, r, c; } tr[2 * N]; int len; void bt(int l, int r) { len++; int now = len; tr[now].l = l; tr[now].r = r; tr[now].lc = tr[now].rc = -1; if (l == r) tr[now].c = 0; else { int mid = (l + r) / 2; tr[now].lc = len + 1; bt(l, mid); tr[now].rc = len + 1; bt(mid + 1, r); tr[now].c = 0; } } void change(int now, int x, int c) { if (tr[now].l == tr[now].r) { tr[now].c = c; return; } int mid = (tr[now].l + tr[now].r) / 2, lc = tr[now].lc, rc = tr[now].rc; if (x <= mid) change(lc, x, c); else change(rc, x, c); tr[now].c = max(tr[lc].c, tr[rc].c); } int findmax(int now, int l, int r) { if (tr[now].l == l && tr[now].r == r) return tr[now].c; int mid = (tr[now].l + tr[now].r) / 2, lc = tr[now].lc, rc = tr[now].rc; if (r <= mid) return findmax(lc, l, r); else if (l >= mid + 1) return findmax(rc, l, r); else return max(findmax(lc, l, mid), findmax(rc, mid + 1, r)); } int solve(int x, int y) { int ans = 0; while (t[x].tp != t[y].tp) { if (t[t[x].tp].dep > t[t[y].tp].dep) swap(x, y); ans = max(ans, findmax(1, t[t[y].tp].z, t[y].z)); y = t[t[y].tp].fa; // y跳到自己所在重链起始端的父亲 } if (x == y) return ans; if (t[x].dep > t[y].dep) swap(x, y); ans = max(ans, findmax(1, t[t[x].son].z, t[y].z)); return ans; } int main() { int n; scanf("%d", &n); for (int i = 1; i < n; i++) { scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].c); G[e[i].x].push_back({e[i].y, e[i].c}); G[e[i].y].push_back({e[i].x, e[i].c}); } t[0] = tnode{0, 0, 0, 0, 0, 0}; dfs1(1, 0); dfs2(1, 1); len = 0; bt(1, z); for (int i = 1; i < n; i++) { if (t[e[i].x].dep > t[e[i].y].dep) swap(e[i].x, e[i].y); change(1, t[e[i].y].z, e[i].c); } char s[20]; while (scanf("%s", s) != EOF && s[0] != 'D') { int x, y; scanf("%d%d", &x, &y); if (s[0] == 'Q') printf("%d\n", solve(x, y)); else change(1, t[e[x].y].z, y); } return 0; }
- 1
信息
- ID
- 545
- 时间
- 1000ms
- 内存
- 2048MiB
- 难度
- 9
- 标签
- 递交数
- 92
- 已通过
- 4
- 上传者