现在的位置: 首页 > 综合 > 正文

【最小点覆盖(树形dp)】PKU-3659-Cell Phone Network

2019年09月23日 ⁄ 综合 ⁄ 共 1204字 ⁄ 字号 评论关闭

题意:一棵树,,删掉一个节点,,可以消灭自己和与其相邻的节点,,,问最少删掉几个节点可以消灭所有的节点?

思路:树形dp,分三个状态,首先dp[i][j]表示以这点为跟的子树的后代都被消灭了,而dp[i][0]不删除且不被其相邻的点消灭,dp[i][1]表示这点不删除但被其相邻的点消灭,dp[i][2]表示这点删除,然后就是不同状态之间的转移了,具体看代码。

题目

#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#include<cmath>
#include<set>
using namespace std;
#define LL long long
#define N 10005
#define exp 1e-6
#define mod 9973
#define inf 10001
int cnt,dp[N][3],head[N];
struct
{
    int v,to;
}edge[2*N];
void add(int fa,int son)
{
    edge[cnt].to=head[fa];
    edge[cnt].v=son;
    head[fa]=cnt++;
}
void dfs(int now,int pre)
{
    dp[now][0]=0;
    dp[now][1]=0;
    dp[now][2]=1;
    int d,m;
    d=0;
    m=inf;
    bool flag=false;
    for(int i=head[now];i!=-1;i=edge[i].to)
    {
        int u=edge[i].v;
        if(u==pre)continue;
        flag=true;
        dfs(u,now);
        dp[now][0]+=dp[u][1];
        dp[now][1]+=min(dp[u][1],dp[u][2]);
        if(dp[u][1]>=dp[u][2])d=1;
        else m=min(m,dp[u][2]-dp[u][1]);
        dp[now][2]+=min(min(dp[u][0],dp[u][1]),dp[u][2]);
    }
    if(dp[now][1]==0)dp[now][1]=inf;
    if(!d&&flag)dp[now][1]+=m;
}
int main()
{
    //freopen("a.txt","r",stdin);
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        cnt=0;
        memset(head,-1,sizeof(head));
        for(int i=1;i<n;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y);
            add(y,x);
        }
        if(n==1)
        {
            printf("1\n");
            continue;
        }
        dfs(1,0);
        printf("%d\n",min(dp[1][1],dp[1][2]));
    }
}


抱歉!评论已关闭.