1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <cstdio> #include <vector> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; if (flag) x = ~x + 1; } template <class Type, class ...rest> void read(Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write(Type x) { if (x < 0) putchar('-'), x = ~x + 1; if (x > 9) write(x / 10); putchar(x % 10 + '0'); } const int N = 1e5 + 10, M = 8e6 + 10, K = 20; vector <int> g[N]; int n, m, d[N], p[N]; int stmp, id[N], lg[N << 1], st[N << 1][K]; void dfs (int x) { st[id[x] = ++stmp][0] = x; for (int i : g[x]) if (i ^ p[x]) { d[i] = d[p[i] = x] + 1; dfs(i); st[++stmp][0] = x; } } int dmin (int a, int b) { return d[a] < d[b] ? a : b; } void init() { dfs(1); for (int i = 2; i <= stmp; ++i) lg[i] = lg[i >> 1] + 1; for (int k = 1; 1 << k <= stmp; ++k) for (int i = 1; i + (1 << k) - 1 <= stmp; ++i) st[i][k] = dmin(st[i][k - 1], st[i + (1 << k - 1)][k - 1]); } int lca (int a, int b) { a = id[a], b = id[b]; if (a > b) swap(a, b); int k = lg[b - a + 1]; return dmin(st[a][k], st[b - (1 << k) + 1][k]); } struct Node { int l, r, v, p; } tr[M]; int idx; void pushup (int x) { int k = tr[tr[x].l].v >= tr[tr[x].r].v ? tr[x].l : tr[x].r; tr[x].v = tr[k].v, tr[x].p = tr[k].p; } void modify (int &x, int t, int k, int l = 1, int r = 1e5) { if (!x) x = ++idx; if (l == r) return tr[x].v += k, tr[x].p = t, void(); int mid = l + r >> 1; t <= mid ? modify(tr[x].l, t, k, l, mid) : modify(tr[x].r, t, k, mid + 1, r); pushup(x); } int merge (int x, int y, int l = 1, int r = 1e5) { if (!x || !y) return x | y; if (l == r) return tr[x].v += tr[y].v, x; int mid = l + r >> 1; tr[x].l = merge(tr[x].l, tr[y].l, l, mid); tr[x].r = merge(tr[x].r, tr[y].r, mid + 1, r); pushup(x); return x; } void calc (int x) { for (int i : g[x]) if (i ^ p[x]) calc(i), merge(x, i); } int main () { read(n, m); idx = n; for (int i = 1, a, b; i < n; ++i) { read(a, b); g[a].push_back(b), g[b].push_back(a); } init(); for (int i = 1, a, b, c; i <= m; ++i) { read(a, b, c); int t = lca(a, b); modify(a, c, 1), modify(b, c, 1); modify(t, c, -1), modify(p[t], c, -1); } calc(1); for (int i = 1; i <= n; ++i) write(tr[i].v ? tr[i].p : 0), puts(""); return 0; }
|