【虚树,树上差分】P6572 [BOI 2017] Railway
Analysis
对于每一个副部长,我们可以把被他选择的所有边都加上 ,最后 check 有哪些边的权值不小于 即可。
对于 的子任务,我们可以轻松找出两个节点之间的那条链。问题被转化为链加以及最终统计,可以使用树上差分解决。为了统计边权,将边权下放成点权即可。
对于一般情况,我们没法不重复的快速给所有被选择的边都 。考虑建出虚树,注意到虚树的边对应到原图上就是所有被选择的边。我们把虚树上一条边 ,其中 是父节点,对应到原图上 到 (但是不包括 )的这条链上。那么对这些链进行链加即可。时间复杂度 ,这里认为 同阶。
Code
namespace Fusu {
const int maxt = 19;
const int maxn = 100005;
int n, m, t, vistime;
int dfn[maxn], fa[maxn], depth[maxn], l2[maxn], a[maxn], id[maxn], g[maxn], w[maxn], anc[maxt][maxn];
std::vector<int> p, q, e[maxn], ans;
std::vector<std::pair<int, int> > ee[maxn];
void dfs(const int u);
void vt();
void dfs2(const int u);
void Main() {
qr(n); qr(m); qr(t);
for (int u, v, i = 1; i < n; ++i) {
qr(u); qr(v);
ee[u].push_back({v, i});
ee[v].push_back({u, i});
}
for (int i = 0, v = 1 << i; v <= n; v = 1 << ++i) l2[v] = i;
for (int i = 3; i <= n; ++i) if (l2[i] == 0) l2[i] = l2[i - 1];
dfs(1);
for (int s, x; m; --m) {
qr(s);
p.clear();
q.clear();
while (s--) {
qr(x);
p.push_back(x);
}
vt();
}
dfs2(1);
for (int i = 1; i <= n; ++i) if (w[i] >= t) ans.push_back(id[i]);
std::sort(ans.begin(), ans.end());
qw(ans.size(), '\n');
for (auto u : ans) {
qw(u, ' ');
}
putchar('\n');
}
int lca(int u, int v) {
if (depth[u] < depth[v]) std::swap(u, v);
for (int delta = depth[u] - depth[v]; delta; delta -= 1 << l2[delta]) {
u = anc[l2[delta]][u];
}
if (u == v) return u;
for (int i = l2[depth[u]]; ~i; --i) if (anc[i][u] != anc[i][v]) {
u = anc[i][u];
v = anc[i][v];
}
return anc[0][u];
}
int top;
int stk[maxn];
void vt() {
std::sort(p.begin(), p.end(), [](const int x, const int y) { return dfn[x] < dfn[y]; });
stk[top = 1] = 0;
int x, y, z;
for (auto u : p) {
x = stk[top];
if ((z = lca(x, u)) != x) {
while (dfn[y = stk[top - 1]] > dfn[z]) {
g[x] = y; q.push_back(x); x = stk[--top];
}
if (y != z) {
g[x] = z; q.push_back(x);
stk[top] = z;
} else if (top != 1) {
g[x] = y;
q.push_back(x);
--top;
}
}
stk[++top] = u;
}
while (top != 1) {
int x = stk[top], y = stk[--top];
g[x] = y;
q.push_back(x);
}
for (auto u : q) if (g[u]) {
++w[u];
--w[g[u]];
}
}
void dfs(const int u) {
dfn[u] = ++vistime;
depth[u] = depth[fa[u]] + 1;
for (int i = 0, v = anc[i][anc[i][u] = fa[u]]; v; v = anc[i][v]) anc[++i][u] = v;
for (auto v : ee[u]) if (dfn[v.first] == 0) {
fa[v.first] = u;
id[v.first] = v.second;
e[u].push_back(v.first);
dfs(v.first);
}
}
void dfs2(const int u) {
for (auto v : e[u]) {
dfs2(v);
w[u] += w[v];
}
}
} // namespace Fusu