树形DP
显然会想到某个点放或不放守卫来定义状态,但在不放的情况下,需要分类讨论是父亲放还是一个儿子放,于是定义以下状态:
f[root][0]表示自己不放,父亲也不放
f[root][1]表示自己放
f[root][2]表示自己不放,父亲放
则状态转移方程为:
f[root][0]+=min(f[son][0],f[son][1])(如果所有儿子都不放,则f[root][0]应加上s=min(f[son][1]-f[son][0]))
f[root][1]+=min(f[son][1],f[son][2])(f[root][1]赋初值为在此放的花费)
f[root][2]+=min(f[son][0],f[son][1])
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int f[1501][3],c[1501];
int fir[3001],nxt[3001],to[3001],cnt;
int n;
bool vis[1501];
int getint()
{
int num=0,flag=1;char c;
while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;
while(c>='0'&&c<='9')num=num*10+c-48,c=getchar();
return num*flag;
}
void newnote(int u,int v)
{to[++cnt]=v;nxt[cnt]=fir[u],fir[u]=cnt;}
void dfs(int root)
{
int i,s=1<<30;bool p=0;
f[root][1]=c[root];
for(i=fir[root];i;i=nxt[i])
if(!vis[to[i]])
{
vis[to[i]]=1;
dfs(to[i]);
if(f[to[i]][0]<f[to[i]][1])f[root][0]+=f[to[i]][0],s=min(s,f[to[i]][1]-f[to[i]][0]);
else f[root][0]+=f[to[i]][1],p=1;
f[root][1]+=min(f[to[i]][1],f[to[i]][2]);
f[root][2]+=min(f[to[i]][0],f[to[i]][1]);
}
if(!p)f[root][0]+=s;
}
int main()
{
int i,j,x,y;
n=getint();
for(i=1;i<=n;i++)
{
x=getint();c[x]=getint();
for(j=getint();j;j--)y=getint(),newnote(x,y),newnote(y,x);
}
vis[1]=1;dfs(1);
printf("%d",min(f[1][0],f[1][1]));
}