Description
Dear Contestant,
I’m going to have a party at my villa at Hali-Bula to celebrate my
retirement from BCM. I wish I could invite all my co-workers, but
imagine how an employee can enjoy a party when he finds his boss among
the guests! So, I decide not to invite both an employee and his/her
boss. The organizational hierarchy at BCM is such that nobody has more
than one boss, and there is one and only one employee with no boss at
all (the Big Boss)! Can I ask you to please write a program to
determine the maximum number of guests so that no employee is invited
when his/her boss is invited too? I’ve attached the list of employees
and the organizational hierarchy of BCM.Best,
–Brian BennettP.S. I would be very grateful if your program can indicate whether the
list of people is uniquely determined if I choose to invite the
maximum number of guests with that condition.Input
The input consists of multiple test cases. Each test case is started
with a line containing an integer n (1 ≤ n ≤ 200), the number of BCM
employees. The next line contains the name of the Big Boss only. Each
of the following n-1 lines contains the name of an employee together
with the name of his/her boss. All names are strings of at least one
and at most 100 letters and are separated by blanks. The last line of
each test case contains a single 0.Output
For each test case, write a single line containing a number indicating
the maximum number of guests that can be invited according to the
required condition, and a word Yes or No, depending on whether the
list of guests is unique in that case.
树形dp求解最大独立集问题,但是还要求判断唯一性。当且仅当所有选择的子决策都是唯一的,这个决策才是唯一的。
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<vector>
#include<iostream>
using namespace std;
map<string,int> mp;
string fa[210];
int f[210],g[210],n;
vector<int> son[210];
bool uni_f[210],uni_g[210];
void dfs(int u)
{
int i,v;
f[u]=1;
g[u]=0;
uni_f[u]=uni_g[u]=1;
for (i=0;i<son[u].size();i++)
{
dfs(v=son[u][i]);
f[u]+=g[v];
if (!uni_g[v]) uni_f[u]=0;
if (f[v]==g[v])
{
g[u]+=f[v];
uni_g[u]=0;
}
else
{
if (f[v]>g[v])
{
g[u]+=f[v];
if (!uni_f[v]) uni_g[u]=0;
}
else
{
g[u]+=g[v];
if (!uni_g[v]) uni_g[u]=0;
}
}
}
}
int main()
{
int i,j,k,p,q,x,y,z;
string s;
while (scanf("%d",&n)&&n)
{
mp.clear();
for (i=1;i<=n;i++)
son[i].clear();
for (i=1;i<=n;i++)
{
cin>>s;
mp[s]=i;
if (i>1) cin>>fa[i];
}
for (i=2;i<=n;i++)
son[mp[fa[i]]].push_back(i);
dfs(1);
if (f[1]==g[1])
printf("%d No\n",f[1]);
else
{
if (f[1]>g[1])
{
printf("%d ",f[1]);
if (uni_f[1]) printf("Yes\n");
else printf("No\n");
}
else
{
printf("%d ",g[1]);
if (uni_g[1]) printf("Yes\n");
else printf("No\n");
}
}
}
}