UVA

题意:n个人,n-1条上下级关系,除了最顶级的boss,每个人只有一个直接上司,要求某人不能和他的直接上司同时参加聚会,问最多有多少人到场,且方案是否唯一。

分析:求树上的最大独立集。

1、如果某人已选,则他的直接下属一定不能选,dp[cur][1] += dp[child][0];

2、如果某人不选,则他的直接下属可选可不选,则在选与不选中取一个最优的。

3、dp[cur][0]---标号为cur的人不选,以cur为根的树的最大独立集,dp[cur][1]---标号为cur的人已选,以cur为根的树的最大独立集

4、唯一性的传递类似,

如果某人已选,则他的直接下属一定不能选,若他的直接下属不选择而形成的最大独立集不唯一,则加上某人后形成的新的最大独立集也不唯一。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 400 + 10;
const int MAXT = 10000 + 10;
using namespace std;
string a, b;
map<string, int> mp;
vector<int> v[MAXN];
int cnt;
int dp[MAXN][2];
bool uni[MAXN][2];
int getid(string x){
    if(!mp.count(x)) return mp[x] = ++cnt;
    return mp[x];
}
void dfs(int cur){
    int len = v[cur].size();
    if(len == 0){
        dp[cur][0] = 0;
        dp[cur][1] = 1;
        return;
    }
    for(int i = 0; i < len; ++i){
        int child = v[cur][i];
        dfs(child);
        dp[cur][1] += dp[child][0];//某人已选
        if(uni[child][0]){
            uni[cur][1] = 1;
        }
        if(dp[child][0] > dp[child][1]){//某人不选
            dp[cur][0] += dp[child][0];
            if(uni[child][0]){
                uni[cur][0] = 1;
            }
        }
        else{
            dp[cur][0] += dp[child][1];
            if(uni[child][1] || dp[child][0] == dp[child][1]){
                uni[cur][0] = 1;
            }
        }
    }
    ++dp[cur][1];//选择标号为cur的人
}
int main(){
    int n;
    while(scanf("%d", &n) == 1){
        if(!n) return 0;
        cnt = 0;
        mp.clear();
        memset(dp, 0, sizeof dp);
        memset(uni, false, sizeof uni);
        for(int i = 0; i < MAXN; ++i) v[i].clear();
        cin >> a;
        getid(a);
        for(int i = 0; i < n - 1; ++i){
            cin >> a >> b;
            int id1 = getid(a);
            int id2 = getid(b);
            v[id2].push_back(id1);
        }
        dfs(1);
        if(dp[1][0] == dp[1][1]){
            printf("%d No
", dp[1][0]);
        }
        else if(dp[1][0] > dp[1][1]){
            printf("%d %s
", dp[1][0], uni[1][0] ? "No" : "Yes");
        }
        else{
            printf("%d %s
", dp[1][1], uni[1][1] ? "No" : "Yes");
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/7357907.html