题目链接
题意
给你个以 1 1 1 为根节点的树,树有边权 w w w (割断此边),多组询问每次询问给你 m m m 个点,求割断边最小花费使得 1 1 1 到这些点都不连通。
思路
询问如果组数少可以直接
O
(
n
)
O(n)
O(n) 树形dp解决,这题询问很多,但是询问的点集不超过
500000
500000
500000
对于答案来说很多点是没有贡献的,有贡献的点只有所求点 和 所求点之间的
L
C
A
LCA
LCA,重新对这些点建树即虚树。
每个节点的权值为1到节点上最小边权
本代码建树通过
d
f
s
dfs
dfs 序,分情况建,题解区有详细的建树过程。
这里记个代码,这里用树剖求LCA。
代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
namespace shupou {
const ll N = 250005;
const ll M = 250005<<1;
ll first[N], tot;
struct Node {
ll v, w, nxt;
}e[M];
ll deep[N], f[N], sz[N], son[N];
ll cnt, dfn[N], top[N], w[N];
void init() {
memset(first,-1,sizeof(first));
w[1] = 1e18;
tot = 0;
cnt = 0;
deep[0] = 0;
}
void add(ll u, ll v, ll w) {
e[tot].v = v;
e[tot].w = w;
e[tot].nxt = first[u];
first[u] = tot++;
}
void dfs1(ll u, ll fa) {
deep[u] = deep[fa]+1;
f[u] = fa;
sz[u] = 1;
son[u] = 0;
ll maxson = -1;
for(ll i = first[u]; ~i; i = e[i].nxt) {
ll v = e[i].v;
if(v == fa) continue;
w[v] = min(w[u], e[i].w);
dfs1(v,u);
sz[u] += sz[v];
if(sz[v] > maxson) son[u] = v, maxson = sz[v];
}
}
void dfs2(ll u, ll topfa) {
dfn[u] = ++cnt;
top[u] = topfa;
if(!son[u]) return;
dfs2(son[u],topfa);
for(ll i = first[u]; ~i; i = e[i].nxt) {
ll v = e[i].v;
if(v == son[u] || v == f[u]) continue;
dfs2(v,v);
}
}
ll getlca(ll x, ll y) {
while(top[x] != top[y]) {
if(deep[top[x]] < deep[top[y]]) swap(x,y);
x = f[top[x]];
}
return deep[x] > deep[y] ? y : x;
}
}
const ll N = 250005;
bool cmp(ll a, ll b) {
return shupou::dfn[a] < shupou::dfn[b];
}
ll vis[N], sta[N], top;
vector<ll> e[N];
void push(ll x) {
int lc = shupou::getlca(x,sta[top]);
if(lc == sta[top]) {
sta[++top] = x;
return;
}
while(shupou::deep[lc] <= shupou::deep[sta[top-1]]) e[sta[top-1]].push_back(sta[top]), --top;
if(shupou::deep[lc] != shupou::deep[sta[top]]) e[lc].push_back(sta[top]), sta[top] = lc;
sta[++top] = x;
}
ll mp[N];
ll dfs(ll u, ll flag) {
ll tmp = (mp[u]&&(!flag)) ? shupou::w[u] : 0;
for(auto v : e[u]) tmp += dfs(v,flag|mp[u]);
e[u].clear();
return flag ? 0 : min(shupou::w[u], tmp);
}
int main() {
shupou::init();
ll n;
scanf("%lld",&n);
for(ll i = 1; i < n; ++i) {
ll u, v, w;
scanf("%lld%lld%lld",&u,&v,&w);
shupou::add(u,v,w);
shupou::add(v,u,w);
}
shupou::dfs1(1,0);
shupou::dfs2(1,1);
ll t;
scanf("%lld",&t);
while(t--) {
ll m;
scanf("%lld",&m);
for(ll i = 1; i <= m; ++i) scanf("%lld",&vis[i]), mp[vis[i]] = 1;
sort(vis+1,vis+1+m,cmp);
sta[top = 1] = 1; // 根初始进栈
for(ll i = 1; i <= m; ++i) push(vis[i]);
while(top > 1) e[sta[top - 1]].push_back(sta[top]), --top;
printf("%lld\n", dfs(1,0));
for(ll i = 1; i <= m; ++i) mp[vis[i]] = 0;
}
return 0;
}