可以每一次都进行一次树形DP,发现有很多点是没有用的,只需要找出一些关键点来进行树形DP就可以,这就用到了虚树。可以用一个栈来维护一条链构建虚树。
PS:INF
一定要够大!!!!又被SDOI的题坑掉了1H,今年SD省选药丸的节奏
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<cstdio>
#include<queue>
#include<cmath>
#include<set>
#include<map>
#define inf 1e60
#define ll long long
#define N 500009
using namespace std;
int sc()
{
int i=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9')i=i*10+c-'0',c=getchar();
return i*f;
}
ll mn[N],f[N],v[N];
int Head[N],Nxt[N],Lst[N];
int deep[N],size[N],fa[N],top[N];
int head[N],lst[N],nxt[N],S[N];
int h[N],st[N];
int n,cnt,tot,Tot,m;
bool cmp(int x,int y){return S[x]<S[y];}
void insert(int x,int y,int z)
{
lst[++tot]=y;nxt[tot]=head[x];head[x]=tot;v[tot]=z;
lst[++tot]=x;nxt[tot]=head[y];head[y]=tot;v[tot]=z;
}
void Insert(int x,int y)
{
if(x==y)return;
Lst[++Tot]=y;Nxt[Tot]=Head[x];Head[x]=Tot;
}
void dfs(int x,int f)
{
S[x]=++cnt;size[x]=1,fa[x]=f;
for(int i=head[x];i;i=nxt[i])
if(lst[i]!=f)
{
deep[lst[i]]=deep[x]+1;
mn[lst[i]]=min(v[i],mn[x]);
dfs(lst[i],x);
size[x]+=size[lst[i]];
}
}
void _dfs(int x,int htp)
{
int k=0;top[x]=htp;
for(int i=head[x];i;i=nxt[i])
if(lst[i]!=fa[x]&&size[lst[i]]>size[k])k=lst[i];
if(!k)return;_dfs(k,htp);
for(int i=head[x];i;i=nxt[i])
if(lst[i]!=k&&lst[i]!=fa[x])
_dfs(lst[i],lst[i]);
}
int Lca(int x,int y)
{
while(top[x]!=top[y])
{
if(deep[top[x]]<deep[top[y]])swap(x,y);
x=fa[top[x]];
}
return deep[x]>deep[y]?y:x;
}
ll dp(int x)
{
ll tmp=0;
for(int i=Head[x];i;i=Nxt[i])
tmp+=dp(Lst[i]);
Head[x]=0;
return tmp?min(tmp,mn[x]):mn[x];
}
void solve()
{
int n=sc(),top=0;Tot=0;
for(int i=1;i<=n;i++)h[i]=sc();
sort(h+1,h+n+1,cmp);
int tot=1;
for(int i=2;i<=n;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(h[i],st[top]);
while(1)
{
if(deep[f]>=deep[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]);
printf("%lld\n",dp(1));
}
int main()
{
//freopen("2286.in","r",stdin);
//freopen("2286.out","w",stdout);
n=sc();
for(int i=1;i<n;i++)
{
int x=sc(),y=sc(),z=sc();
insert(x,y,z);
}
mn[1]=inf;dfs(1,0);_dfs(1,1);
for(int i=1,m=sc();i<=m;i++)solve();
return 0;
}