UVa1220 - Party at Hali-Bula

本文探讨了一个公司员工聚会安排问题,要求任意员工与其直接上司不能同时到场,通过构建树形结构并运用树形dp算法解决最大独立集问题,同时分析了唯一性方案。

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



题意:一个公司员工要举行聚会,要求任意一个人不能和他的直接上司同时到场,一个员工只有一个支系上司,现在求最多有多少人到场,并且方案是否唯一


分析:分析发现是要求一个树的最大独立集。这里可以用树形dp解决。

定义dp【x】【0】:表示在 i 点不选 i 点的以 x 为子树的最大独立集 而dp【x】【1】 表示x到场的最大独立集

定义f 【x】【0】:表示以x为根且x点不选的子树是否唯一 ,f【x】【1】表示以x为根且x选的子树是否唯一

状态转移方程:dp [ x ] [ 1 ] + = dp [ child ] [ 0 ] ;

 dp [ x ] [ 0 ] +  = max ( dp [ child ] [ 0 ] , dp [ child ] [ 1 ] );

而判断唯一性的方程一样的。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
#define maxn 65540
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 300;

vector<int> child[N];
map<string,int> v;
int dp[N][3];
bool f[N][3]; //唯一性
void DFS(int u)
{
    if(child[u].size()==0)
    {
        dp[u][0]=0;
        dp[u][1]=1;
        return;
    }
    int size=child[u].size();
    for(int i=0;i<size;i++)
    {
        DFS(child[u][i]);
        if(f[child[u][i]][0])
            f[u][1]=1;
        dp[u][1]+=dp[child[u][i]][0];
        if(dp[child[u][i]][0]>dp[child[u][i]][1])
        {
            dp[u][0]+=dp[child[u][i]][0];
            if(f[child[u][i]][0])
                f[u][0]=1;
        }
        else
        {
            dp[u][0]+=dp[child[u][i]][1];
            if(dp[child[u][i]][1]==dp[child[u][i]][0]||f[child[u][i]][1])
                f[u][0]=1;
        }
    }
    dp[u][1]++;
}
int main()
{
    int n;
    while(~scanf("%d",&n) && n)
    {
        memset(dp,0,sizeof(dp));
        memset(f,0,sizeof(f));
        int top = 1;
        string s1,s2;
        cin>>s1;
        v[s1] = top++;
        for(int i=1;i<n;i++)
        {
            cin>>s1>>s2;
            if(!v[s1])
                v[s1]=top++;
            if(!v[s2])
                v[s2]=top++;
            child[v[s2]].push_back(v[s1]);
        }
        DFS(1);
        if(dp[1][1]==dp[1][0])
            printf("%d No\n",dp[1][1]);
        else if(dp[1][1]>dp[1][0])
            printf("%d %s\n",dp[1][1],f[1][1]?"No":"Yes");
        else
            printf("%d %s\n",dp[1][0],f[1][0]?"No":"Yes");
        for(int i = 1;i<=n;i++)
            child[i].clear();
        v.clear();
    }
    return 0;
}


题意:一个公司员工要举行聚会,要求任意一个人不能和他的直接上司同时到场,一个员工只有一个支系上司,现在求最多有多少人到场,并且方案是否唯一


分析:分析发现是要求一个树的最大独立集。这里可以用树形dp解决。

定义dp【x】【0】:表示在 i 点不选 i 点的以 x 为子树的最大独立集 而dp【x】【1】 表示x到场的最大独立集

定义f 【x】【0】:表示以x为根且x点不选的子树是否唯一 ,f【x】【1】表示以x为根且x选的子树是否唯一

状态转移方程:dp [ x ] [ 1 ] + = dp [ child ] [ 0 ] ;

 dp [ x ] [ 0 ] +  = max ( dp [ child ] [ 0 ] , dp [ child ] [ 1 ] );

而判断唯一性的方程一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值