Assign the task
题意:
一棵树
两种操作
1. "C x" 查询节点x的颜色
2."T x y" 将以x为根节点的子树的颜色全部染为k
题解:
dfs序+线段树
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int N = 5e5 + 10; struct node { int l, r; int v; int lazy; } tr[N << 2]; int n; int h[N], ne[N << 1], e[N << 1], idx; int L[N], R[N], tot; int rt; int fa[N]; void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx++; } void dfs(int u, int fa) { L[u] = ++tot; for (int i = h[u]; ~i; i = ne[i]) { int j = e[i]; if (j == fa) continue; dfs(j, u); } R[u] = tot; } void pushdown(int u) { if (tr[u].l == tr[u].r) { tr[u].lazy = -1; return; } if (tr[u].lazy == 0) return; tr[u << 1].lazy = 1; tr[u << 1 | 1].lazy = 1; tr[u << 1].v = tr[u].v; tr[u << 1 | 1].v = tr[u].v; tr[u].lazy = 0; } void build(int u, int l, int r) { if (l == r) { tr[u] = {l, r, -1, 0}; return; } else { tr[u] = {l, r, -1, 0}; int mid = l + r >> 1; build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r); return; } } void modify(int u, int l, int r, int x) { if (tr[u].r <= r && tr[u].l >= l) { tr[u].v = x; tr[u].lazy = 1; return; } pushdown(u); int mid = tr[u].l + tr[u].r >> 1; if (l <= mid) modify(u << 1, l, r, x); if (r > mid) modify(u << 1 | 1, l, r, x); return; } int query(int u, int x) { // if (x >= tr[u].l && x <= tr[u].r && tr[u].lazy == 1) return tr[u].v; if (tr[u].l == x && tr[u].r == x) return tr[u].v; pushdown(u); int mid = tr[u].l + tr[u].r >> 1; if (x <= mid) return query(u << 1, x); else return query(u << 1 | 1, x); } int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int t; cin >> t; for (int _ = 1; _ <= t; _++) { printf("Case #%d: ", _); idx = 0; tot = 0; memset(h, -1, sizeof h); memset(fa, 0, sizeof fa); cin >> n; build(1, 1, n); for (int i = 1; i < n; i++) { int a, b; cin >> a >> b; add(b, a); fa[a] = b; } for (int i = 1; i <= n; i++) { if (!fa[i]) { dfs(i, 0); } } // cout << "rt = " << rt << endl; // dfs(rt, 0); int m; cin >> m; while (m--) { char op[2]; int x; scanf("%s %d", op, &x); cin >> op >> x; if (op[0] == 'C') printf("%d ", query(1, L[x])); else { int k; scanf("%d", &k); modify(1, L[x], R[x], k); } } } }