因为听说多校第一场的09可以用虚树来做,于是赶紧趁着没比赛补一发相关知识点。
卧槽写完这篇题解之后,突然发现多校09题解给的方法不就是维护一颗动态虚树嘛!
只不过说虚树是动态的,你需要将点插入虚树中,就要动态维护这个树的权值。
事实上虚树就是通过重新建树,使得树上的“无用决策点”全部去掉(当然相关信息必须要之前就维护好)。
http://lazycal.logdown.com/posts/202331-bzoj3572
虚树的构建方法
code:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL INF = 1e17;
const int N = 250005;
const int M = 19;
struct edge{
int to,next;
LL c;
};
edge e[N << 1];
int head[N],sz;
int fa[N][M],dep[N];
int DFN[N],Time;
LL cost[N];
inline bool cmp1(int x,int y){/*{{{*/
return DFN[x] < DFN[y];
}
inline bool cmp2(int x,int y){
return dep[x] > dep[y];
}
void init(){
memset(head,-1,sizeof(head));
sz = Time = 0;
cost[1] = INF;
}
void addedge(int u,int v,LL c){
e[sz].to = v;
e[sz].c = c;
e[sz].next = head[u];
head[u] = sz ++;
}
void dfs(int u,int f){
fa[u][0] = f;
DFN[u] = ++ Time;
for(int i = 1 ; i < M ; i ++)
fa[u][i] = fa[ fa[u][i - 1] ][i - 1];
for(int i = head[u] ; i != -1 ; i = e[i].next){
int v = e[i].to;
if(v == f) continue;
cost[v] = min(cost[u],e[i].c);
dep[v] = dep[u] + 1;
dfs(v,u);
}
}
int find(int x,int k){
for(int i = 0 ; k ; i ++,k >>= 1)
if(k & 1) x = fa[x][i];
return x;
}
int lca(int x,int y){
if(dep[x] > dep[y]) swap(x,y);
y = find(y,dep[y] - dep[x]);
if(x != y){
for(int i = M - 1 ; i >= 0 ; i --){
if(fa[x][i] != fa[y][i])
x = fa[x][i],y = fa[y][i];
}
x = fa[x][0];
y = fa[y][0];
}
return x;
}/*}}}*/
int n,m;
int h[N],t[N],tot;
int father[N],son[N];
int S[N],top;
LL dp[N];
void build(int k){/*{{{*/
tot = top = 0;
for(int i = 1 ; i <= k ; i ++){
int p = h[i];
if(!top){
father[p] = 0;
S[++ top] = p;
t[++ tot] = p;
}
else{
int anc = lca(p,S[top]);
while(top && dep[anc] < dep[ S[top] ]){
if(dep[ S[top - 1] ] <= dep[anc])
father[S[top]] = anc;
-- top;
}
if(anc != S[top]){
father[anc] = S[top];
t[++ tot] = anc;
S[++ top] = anc;
}
father[p] = S[top];
t[++ tot] = p;
S[++ top] = p;
}
}
}/*}}}*/
void debug(){
for(int i = 1 ; i <= tot ; i ++) printf("%d ",t[i]);
printf("\n");
for(int i = 1 ; i <= tot ; i ++) printf("%d ",father[ t[i] ]);
printf("\n");
}
void deal(){
int k;
scanf("%d",&k);
for(int i = 1 ; i <= k ; i ++){
scanf("%d",&h[i]);
}
sort(h + 1,h + k + 1,cmp1);
build(k);
sort(t + 1,t + tot + 1,cmp2);
son[0] = dp[0] = 0;
for(int i = 1 ; i <= tot ; i ++)
son[ t[i] ] = dp[ t[i] ] = 0;
for(int i = 1 ; i <= k ; i ++)
son[ h[i] ] = 1,dp[ h[i] ] = INF;
for(int i = 1 ; i <= tot ; i ++){
int x = t[i];
dp[x] = min(dp[x],cost[x]);
son[ father[x] ] |= son[x];
dp[ father[x] ] += dp[x];
}
printf("%lld\n",dp[ t[tot] ]);
}
void solve(){
int x,y;
LL c;
init();
for(int i = 1 ; i < n ; i ++){
scanf("%d%d%lld",&x,&y,&c);
addedge(x,y,c);
addedge(y,x,c);
}
dfs(1,0);
scanf("%d",&m);
while(m --) deal();
}
int main()
{
while(~scanf("%d",&n)) solve();
return 0;
}