bzoj
2286√
题意
一棵n(250000)小于个点的有边权树,m次询问,每次询问断开k个点(两两不相连)的最小花费(所有k加起来小于500000)
分析
嗯~显然虚树~~
虚树搞完以后的问题就变成了一道朴素的树形dp题了。
显然:dp[i]=min(val[i],Σdp[j](j为i的儿子)),val[i]表示将i和根节点分离的代价(预处理一波就好了)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=250100;
int bh[N],q[N],h[N],st[N],dep[N],fa[N][21];
int top,tt,n,m,x,y,z,tot,cnt,a[N],pos[N];
long long mn[N],f[N];
struct edge{int y,z,next;}g[N*2],b[N*2];
void addpath(int x,int y,int z)
{
g[++tot].y=y;
g[tot].next=h[x];
g[tot].z=z;
h[x]=tot;
}
void adp(int x,int y)
{
if (x==y) return;
b[++tt].y=y;
b[tt].next=bh[x];
bh[x]=tt;
}
void dfs(int x)
{
pos[x]=++cnt;
for (int i=h[x];i;i=g[i].next)
if (g[i].y!=fa[x][0])
{
mn[g[i].y]=min(mn[x],(long long)g[i].z);
fa[g[i].y][0]=x;
dep[g[i].y]=dep[x]+1;
dfs(g[i].y);
}
}
int cmp(int a,int b)
{
return pos[a]<pos[b];
}
int lca(int x,int y)
{
if (dep[x]<dep[y])
swap(x,y);
for (int i=19;i>=0;i--)
if (dep[x]-dep[y]>=(1<<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)
{
f[x]=mn[x];long long res=0;
for (int i=bh[x];i;i=b[i].next)
{
dp(b[i].y);
res+=f[b[i].y];
}
bh[x]=0;
if (res && f[x]>res)
f[x]=res;
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d",&n);
for (int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
addpath(x,y,z);
addpath(y,x,z);
}
mn[1]=1e60;dfs(1);
for (int j=1;j<=20;j++)
for (int i=1;i<=n;i++)
fa[i][j]=fa[fa[i][j-1]][j-1];
int ttt;scanf("%d",&ttt);
for (int i=1;i<=ttt;i++)
{
scanf("%d",&m);
for (int j=1;j<=m;j++)
scanf("%d",a+j);
sort(a+1,a+m+1,cmp);
q[tot=1]=a[1];tt=0;
for (int i=2;i<=m;i++)
if (lca(q[tot],a[i])!=q[tot])
q[++tot]=a[i];
st[top=1]=1;
for (int j=1;j<=tot;j++)
{
int now=q[j],f=lca(now,st[top]);
while (1)
{
if (dep[f]>=dep[st[top-1]])
{
adp(f,st[top--]);
if (st[top]!=f) st[++top]=f;
break;
}
adp(st[top-1],st[top]);top--;
}
if (st[top]!=now) st[++top]=now;
}
while (--top) adp(st[top],st[top+1]);
dp(1);
printf("%lld\n",f[1]);
}
}
3572√
3879(后缀树+虚树)
3991√
(set维护dfs序答案为相邻的距离和最后加上第一个和最后一个的距离。是虚树所有边的两倍)