题目大意:
给定一棵根节点为1的带边权的树。
每次给定一些点,求把这些点与树根断开的最小花费。
题目分析:
我们可以O(n)处理出每个点与根断开的最小花费,即该节点到根的路径上的最小边权。
然后我们对于每一个询问,可以把询问的点打上标记,然后可以O(n)动态规划求解。
但是O(n)的时间复杂度接受不了,而且我们发现每次询问并不会询问所有的点,而且询问的总点数不超过50w。
这样我们可以每次只把这些询问的点拎出来,建一棵虚树,在虚树上dp。这样时间复杂度上界为O(总点数*2)
这道题就可以过了。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
#define N 250020
using namespace std;
inline int Min(int x,int y) { return x<y?x:y; }
inline long long Min(long long x,long long y) { return x<y?x:y; }
void read(int &c)
{
static char ch;
c=0; ch=getchar();
while(ch>'9' || ch<'0') ch=getchar();
while(ch<='9' && ch>='0')
{
c=(c<<1)+(c<<3)+ch-'0';
ch=getchar();
}
return;
}
int fir[N],nes[N<<1],v[N<<1],q[N<<1],tot=1;
int cost[N],a[N],xl[N],sta[N];
int fa[N][19],dep[N],pos[N],top;
int n,m,K;
bool b[N];
long long f[N],ans;
void edge(int x,int y,int z=0)
{
tot++;
v[tot]=y;
q[tot]=z;
nes[tot]=fir[x];
fir[x]=tot;
return;
}
#define Edge_Round(x,y,z) edge(x,y,z),edge(y,x,z)
void dfs(int c)
{
pos[c]=++top;
dep[c]=dep[fa[c][0]]+1;
for(int i=1;i<19;i++)
fa[c][i]=fa[fa[c][i-1]][i-1];
for(int t=fir[c];t;t=nes[t])
{
if(v[t]==fa[c][0]) continue;
fa[v[t]][0]=c;
cost[v[t]]=Min(cost[c],q[t]);
dfs(v[t]);
}
}
int lca(int x,int y)
{
if(dep[x]<dep[y]) swap(x,y);
for(int i=18;~i;i--)
if(dep[fa[x][i]]>=dep[y]) x=fa[x][i];
if(x==y) return x;
for(int i=18;~i;i--)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
bool cmp(int a,int b) { return pos[a]<pos[b]; }
void dfs2(int c)
{
xl[++top]=c;
long long tmp=0;
for(int t=fir[c];t;t=nes[t])
{
dfs2(v[t]);
tmp+=f[v[t]];
}
if(c==1) f[c]=tmp;
else if(b[c]) f[c]=cost[c];
else f[c]=Min(tmp,(long long)cost[c]);
return;
}
void query()
{
read(K);
for(int i=1;i<=K;i++) read(a[i]),b[a[i]]=true;
sort(a+1,a+1+K,cmp);
top=0;tot=1;
if(a[1]!=1) sta[++top]=1;
for(int i=1;i<=K;i++)
{
int LCA=lca(sta[top],a[i]);
while(top>0)
{
if(top>1 && dep[sta[top-1]]>dep[LCA]) edge(sta[top-1],sta[top]),top--;
else if(dep[sta[top]]>dep[LCA]) { edge(LCA,sta[top]),top--; break;}
else break;
}
if(LCA!=sta[top]) sta[++top]=LCA;
sta[++top]=a[i];
}
while(top>1) edge(sta[top-1],sta[top]),top--;
top=0;
dfs2(1);
printf("%lld\n",f[1]);
for(int i=1;i<=top;i++)
{
b[xl[i]]=false;
fir[xl[i]]=0;
}
return;
}
int main()
{
read(n);
for(int i=1,x,y,z;i<n;i++)
{
read(x),read(y),read(z);
Edge_Round(x,y,z);
}
cost[1]=0x1f1f1f1f;
dfs(1);
memset(fir,0,sizeof(fir));
read(m);
while(m--) query();
return 0;
}