dp uva1220

题目链接


树的最大独立集问题

d(u,0) 表示以u为根的子树中,不选u点能得到的最大人数 f(u,0)=1表示唯一,否则不唯一

d(u,1)--------------------------------选u       f(u,1)=1表示唯一,否则不唯一


#include <bits/stdc++.h>
using namespace std;

const int maxn = 200+5;
int n,cnt,d[maxn][2],f[maxn][2];
vector<int> sons[maxn];
map<string,int> dict;

int ID(string s){
	if(!dict.count(s)) dict[s] = cnt++;
	return dict[s];
}

int dp(int u,int k){
	d[u][k] = k;
	f[u][k] = 1;
	for(int i=0; i<sons[u].size(); i++){
		int v = sons[u][i];
		if(k==1){
			d[u][k] += dp(v,0);
			if(!f[v][0]) f[u][k] = 0;
		}else{
			d[u][k] += max(dp(v,0),dp(v,1));
			if(d[v][0]==d[v][1]) f[u][k] = 0;
			else if(d[v][0]>d[v][1] && !f[v][0]) f[u][k] = 0;
			else if(d[v][1]>d[v][0] && !f[v][1]) f[u][k] = 0;
		}
	}
	return d[u][k];
	
}

int main(){
	string s,s2;
	while(cin >> n >> s){
		cnt = 0;
		for(int i=0; i<n; i++) sons[i].clear();
		dict.clear();

		ID(s);
		for(int i=0; i<n-1; i++){
			cin >> s >> s2;
			sons[ID(s2)].push_back(ID(s));
		}
		int ans;
		ans = max(dp(0,0),dp(0,1));
		printf("%d ", ans);

		bool unique = false;
		if(d[0][0]>d[0][1] && f[0][0]) unique = true;
		if(d[0][1]>d[0][0] && f[0][1]) unique = true;

		if(unique) printf("Yes\n");
		else printf("No\n");

	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值