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 110 111
| #include<bits/stdc++.h> using namespace std;
#define pb push_back
inline int rd() { int x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
#define N 100007
int totnode;
struct node {int ls, rs, mx, mxp;} c[N << 6];
inline void pushup(int rt) { if (c[c[rt].ls].mx >= c[c[rt].rs].mx) { c[rt].mx = c[c[rt].ls].mx; c[rt].mxp = c[c[rt].ls].mxp; } else { c[rt].mx = c[c[rt].rs].mx; c[rt].mxp = c[c[rt].rs].mxp; } }
void upd(int &rt, int l, int r, int p, int x) { if (!rt) rt = ++totnode; if (l == r) { c[rt].mx += x; c[rt].mxp = p; return; } int mid = (l + r) >> 1; p <= mid ? upd(c[rt].ls, l, mid, p, x) : upd(c[rt].rs, mid + 1, r, p, x); pushup(rt); }
int merge(int rta, int rtb, int l, int r) { if (!rta || !rtb) return rta + rtb; if (l == r) { c[rta].mx += c[rtb].mx; return rta; } int mid = (l + r) >> 1; c[rta].ls = merge(c[rta].ls, c[rtb].ls, l, mid); c[rta].rs = merge(c[rta].rs, c[rtb].rs, mid + 1, r); pushup(rta); return rta; }
int rot[N], ans[N];
vector<int> e[N];
int dep[N], f[N], mxson[N], sz[N], top[N];
void dfs1(int u, int d) { dep[u] = d; sz[u] = 1; int mxid = 0; for (auto v : e[u]) if (!f[v]) { f[v] = u; dfs1(v, d + 1); sz[u] += sz[v]; if (sz[v] > sz[mxid]) mxid = v; } mxson[u] = mxid; }
void dfs2(int u, int t) { top[u] = t; if (mxson[u]) dfs2(mxson[u], t); for (auto v : e[u]) if (!top[v]) dfs2(v, v); }
inline int lca(int u, int v) { while (top[u] != top[v]) dep[top[u]] > dep[top[v]] ? u = f[top[u]] : v = f[top[v]]; return dep[u] > dep[v] ? v : u; }
void dfs(int u, int fa) { for (auto v : e[u]) if (v != fa) { dfs(v, u); rot[u] = merge(rot[u], rot[v], 1, 100000); } ans[u] = c[rot[u]].mx ? c[rot[u]].mxp : 0; }
int main() { int n = rd(), m = rd(); for (int i = 1; i < n; ++i) { int u = rd(), v = rd(); e[u].pb(v); e[v].pb(u); } f[1] = 1; dfs1(1, 1); dfs2(1, 1); for (int i = 1; i <= m; ++i) { int x = rd(), y = rd(), z = rd(); int anc = lca(x, y); upd(rot[x], 1, 100000, z, 1); upd(rot[y], 1, 100000, z, 1); upd(rot[anc], 1, 100000, z, -1); if (f[anc] != anc) upd(rot[f[anc]], 1, 100000, z, -1); } dfs(1, 1); for (int i = 1; i <= n; ++i) printf("%d\n", ans[i]); return 0; }
|