1 条题解
-
0
注意负权值
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N = 3e4 + 10; const LL inf = 1e9; LL num[N]; vector<int> G[N]; int fa[N], siz[N], dep[N], son[N]; void fir_dfs(int x, int x_fa) { fa[x] = x_fa; siz[x] = 1; son[x] = -1; dep[x] = dep[x_fa] + 1; for (int y : G[x]) if (y != x_fa) { fir_dfs(y, x); if ( (son[x] == -1) || (siz[son[x]] < siz[y]) ) { son[x] = y; } siz[x] += siz[y]; } } int tsp, dfn[N], r_dfn[N], top[N]; void sec_dfs(int x, int tp) { tsp ++; dfn[x] = tsp; r_dfn[dfn[x]] = x; top[x] = tp; if (son[x] != -1) { sec_dfs(son[x], tp); } for (int y : G[x]) if (son[x] != y && y != fa[x]) { sec_dfs(y, y); } } #define lc(p) p << 1 #define rc(p) (p << 1) | 1 struct node { int l, r; LL mx, sum; } tr[4 * N]; void pushup(int p) { tr[p].sum = tr[lc(p)].sum + tr[rc(p)].sum; tr[p].mx = max(tr[lc(p)].mx, tr[rc(p)].mx); } void build(int p, int l, int r) { tr[p] = {l, r, -inf, -inf}; if (l == r) { tr[p] = {l, r, num[r_dfn[l]], num[r_dfn[l]]}; return ; } int mid = (l + r) >> 1; build(lc(p), l, mid); build(rc(p), mid + 1, r); pushup(p); } void change(int p, int x, LL c) { if (tr[p].l > x || tr[p].r < x) { return ; } if (tr[p].l == tr[p].r) { tr[p].mx = tr[p].sum = c; return ; } change(lc(p), x, c); change(rc(p), x, c); pushup(p); } LL find_max(int p, int l, int r) { if (tr[p].l > r || tr[p].r < l) { return -inf; } if (l <= tr[p].l && tr[p].r <= r) { return tr[p].mx; } return max(find_max(lc(p), l, r), find_max(rc(p), l, r)); } LL get_sum(int p, int l, int r) { if (tr[p].l > r || tr[p].r < l) { return 0; } if (l <= tr[p].l && tr[p].r <= r) { return tr[p].sum; } return get_sum(lc(p), l, r) + get_sum(rc(p), l, r); } LL query_max(int x, int y) { LL res = -inf; while (top[x] != top[y]) { if (dep[top[x]] < dep[top[y]]) { swap(x, y); } res = max(res, find_max(1, dfn[top[x]], dfn[x])); x = fa[top[x]]; } if (dep[x] > dep[y]) { swap(x, y); } res = max(res, find_max(1, dfn[x], dfn[y])); return res; } LL query_sum(int x, int y) { LL res = 0; while (top[x] != top[y]) { if (dep[top[x]] < dep[top[y]]) { swap(x, y); } res += get_sum(1, dfn[top[x]], dfn[x]); x = fa[top[x]]; } if (dep[x] > dep[y]) { swap(x, y); } res += get_sum(1, dfn[x], dfn[y]); return res; } int main () { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 1; i < n; i ++) { int x, y; cin >> x >> y; G[x].push_back(y); G[y].push_back(x); } for (int i = 1; i <= n; i ++) { cin >> num[i]; } dep[0] = 0; fir_dfs(1, 0); tsp = 0; sec_dfs(1, 1); build(1, 1, n); int q; cin >> q; for (int i = 1; i <= q; i ++) { char s[10]; cin >> s; if(s[0] == 'C') { int x; LL c; cin >> x >> c; change(1, dfn[x], c); } else if (s[0] == 'Q' && s[1] == 'M') { int x, y; cin >> x >> y; cout << query_max(x, y) << "\n"; } else { int x, y; cin >> x >> y; cout << query_sum(x, y) << "\n"; } } return 0; }
- 1
信息
- ID
- 2689
- 时间
- 1000ms
- 内存
- 512MiB
- 难度
- 4
- 标签
- 递交数
- 26
- 已通过
- 17
- 上传者