虚树学习笔记

· · 个人记录

用于解决一类树形dp问题。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0; int f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

typedef long long ll;
const ll INF = 1e60;
const int MAXN = 250005;
struct Node {int to,val;};
std::vector<Node> G[MAXN];
std::vector<int> adj[MAXN];
int last[MAXN],last2[MAXN],fa[MAXN][20],bin[20];
int h[MAXN],mark[MAXN],dep[MAXN],st[MAXN];
ll mn[MAXN],f[MAXN];
int n,m,cnt,ind,top;

inline void addedge(int u,int v,int w)
{
    G[u].push_back(Node{v,w});
    G[v].push_back(Node{u,w});
}

inline void insert(int u,int v)
{
    if(u==v) return;
    adj[u].push_back(v);
}

inline bool cmp(int a,int b)
{return mark[a]<mark[b];}

void pre(int x)
{
    int sz=G[x].size(); mark[x]=++ind;
    for(int i=1; bin[i]<=dep[x]; i++)
        fa[x][i]=fa[fa[x][i-1]][i-1];
    for (int i = 0; i < sz; ++i)
    {
        int y=G[x][i].to;
        if(y==fa[x][0]) continue;
        mn[y]=min(mn[x],(ll)G[x][i].val);
        dep[y]=dep[x]+1;
        fa[y][0]=x; pre(y);
    }
}

inline int lca(int x,int y)
{
    if(dep[x]<dep[y]) swap(x,y);
    int t=dep[x]-dep[y];
    for(int i=0; bin[i]<=t; i++)
        if(t&bin[i]) x=fa[x][i];
    for(int i=19; i>=0; i--)
        if(fa[x][i]!=fa[y][i])
            x=fa[x][i],y=fa[y][i];
    if(x==y) return x;
    return fa[x][0];
}

void dp(int x)
{
    ll tmp=0; f[x]=mn[x];
    int sz=adj[x].size();
    for (int i = 0; i < sz; ++i)
    {
        int y=adj[x][i];
        dp(y); tmp+=f[y];
    }
    adj[x].clear();
    if(tmp==0) f[x]=mn[x];
    else if(tmp<=f[x]) f[x]=tmp;
}

inline void solve()
{

    int K=read(); cnt=0;
    for(int i=1; i<=K; i++)
        h[i]=read();
    sort(h+1,h+K+1,cmp);
    int tot=0; h[++tot]=h[1];
    for(int i=2; i<=K; i++)
        if(lca(h[tot],h[i])!=h[tot])
            h[++tot]=h[i];
    st[++top]=1;
    for(int i=1; i<=tot; i++)
    {
        int now=h[i],f=lca(now,st[top]);
        while(1)
        {
            if(dep[f]>=dep[st[top-1]])
            {
                insert(f,st[top--]);
                if(st[top]!=f) st[++top]=f;
                break;
            }
            insert(st[top-1],st[top]); top--;
        }
        if(st[top]!=now) st[++top]=now;
    }
    while(--top)
        insert(st[top],st[top+1]);
    dp(1); printf("%lld\n",f[1]);
}

int main(int argc, char const *argv[])
{
    n=read(); bin[0]=1;
    for(int i=1; i<20; i++)
        bin[i]=bin[i-1]<<1;
    for(int i=1; i<n; i++)
    {
        int u=read(),v=read(),w=read();
        addedge(u,v,w);
    }
    mn[1]=INF; pre(1); m=read();
    for(int i=1; i<=m; i++)
        solve();
    return 0;
}