vijos 小胖守皇宫

这篇博客探讨了如何使用树形动态规划(DP)解决一个关于放置守卫的皇宫问题。博客介绍了三个状态定义:自己不放且父亲不放、自己放、自己不放但父亲放,并给出了相应状态转移方程。博主分享了实现这一策略的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开题目

树形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]));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值