题解
这题做法很多呢!
目前我只试过线段树合并,因为最近在学
对于每一个点开一颗关于粮食类型的线段树
维护数量和区间最多的类型
然后考虑到合并子树的过程就类似于树上差分后做前缀和
所以我们可以树上差分一下,省去树剖的一只 (log) (但求 ( ext {lca}) 还是打了树剖)
最后就是套路地合并过程了!!
(Code)
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 1e5 + 5;
int n, m, Len, h[N], tot;
struct edge{int to, nxt;}e[N << 1];
inline void add(int u, int v){e[++tot] = edge{v, h[u]}, h[u] = tot;}
int top[N], fa[N], dep[N], siz[N], son[N];
void dfs1(int x)
{
siz[x] = 1;
for(register int i = h[x]; i; i = e[i].nxt)
{
int v = e[i].to;
if (v == fa[x]) continue;
fa[v] = x, dep[v] = dep[x] + 1, dfs1(v), siz[x] += siz[v];
if (siz[v] > siz[son[x]]) son[x] = v;
}
}
void dfs2(int x)
{
if (son[x]) top[son[x]] = top[x], dfs2(son[x]);
for(register int i = h[x]; i; i = e[i].nxt)
{
int v = e[i].to;
if (v == fa[x] || v == son[x]) continue;
top[v] = v, dfs2(v);
}
}
inline int LCA(int x, int y)
{
int fx = top[x], fy = top[y];
while (fx ^ fy)
{
if (dep[fx] > dep[fy]) x = fa[fx], fx = top[x];
else y = fa[fy], fy = top[y];
}
if (dep[x] < dep[y]) return x;
return y;
}
struct ask{int x, y, z;}a[N];
int size, rt[N];
struct Tree{int sum, col, ls, rs;}seg[N << 6];
inline void pushup(int p)
{
if (seg[seg[p].ls].sum >= seg[seg[p].rs].sum)
{
seg[p].sum = seg[seg[p].ls].sum;
seg[p].col = seg[seg[p].ls].col;
}
else{
seg[p].sum = seg[seg[p].rs].sum;
seg[p].col = seg[seg[p].rs].col;
}
}
void insert(int &p, int l, int r, int x, int v)
{
if (!p) p = ++size;
if (l == r)
{
seg[p].sum += v, seg[p].col = l;
return;
}
int mid = (l + r) >> 1;
if (x <= mid) insert(seg[p].ls, l, mid, x, v);
else insert(seg[p].rs, mid + 1, r, x, v);
pushup(p);
}
int merge(int x, int y, int l, int r)
{
if (!x || !y) return x | y;
if (l == r)
{
seg[x].sum += seg[y].sum, seg[x].col = l;
return x;
}
int mid = (l + r) >> 1;
seg[x].ls = merge(seg[x].ls, seg[y].ls, l, mid);
seg[x].rs = merge(seg[x].rs, seg[y].rs, mid + 1, r);
pushup(x); return x;
}
int ans[N];
void dfs(int x)
{
for(register int i = h[x]; i; i = e[i].nxt)
{
int v = e[i].to;
if (v == fa[x]) continue;
dfs(v), rt[x] = merge(rt[x], rt[v], 1, Len);
}
if (seg[rt[x]].sum) ans[x] = seg[rt[x]].col;
}
int main()
{
scanf("%d%d", &n, &m);
int x, y, z;
for(register int i = 1; i < n; i++) scanf("%d%d", &x, &y), add(x, y), add(y, x);
dfs1(1), top[1] = 1, dfs2(1);
for(register int i = 1; i <= m; i++)
scanf("%d%d%d", &x, &y, &z), a[i] = ask{x, y, z}, Len = max(Len, z);
for(register int i = 1; i <= m; i++)
{
int lca = LCA(a[i].x, a[i].y);
insert(rt[a[i].x], 1, Len, a[i].z, 1), insert(rt[a[i].y], 1, Len, a[i].z, 1);
insert(rt[lca], 1, Len, a[i].z, -1);
if (fa[lca]) insert(rt[fa[lca]], 1, Len, a[i].z, -1);
}
dfs(1);
for(register int i = 1; i <= n; i++) printf("%d
", ans[i]);
}