按照紫书的思路,递归求解即可,同时注意最终结束的条件是n=0,被这个点卡了很久,以下是源代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int n;
map<string, int> nameToId;
int amount;
int total[210][2];
bool only[210][2];
int getId(const string& name){
if (nameToId.find(name) == nameToId.end())
nameToId[name] = amount++;
return nameToId[name];
}
bool judge(int ind){
if (total[ind][0] == total[ind][1]) return false;
else if (total[ind][0] > total[ind][1]) return only[ind][0];
else return only[ind][1];
}
int dp(vector<int>* son,int ind,int select){
total[ind][select] = select;
only[ind][select] = true;
for (int i = 0; i < son[ind].size(); i++){
int index1 = son[ind][i];
if (select){
total[ind][select] += dp(son,index1,0);
if (!only[index1][0]) only[ind][select] =false;
}
else{
total[ind][select] += max(dp(son,index1,0),dp(son,index1,1));
if (!judge(index1))
only[ind][select] = false;
}
}
return total[ind][select];
}
int main(){
while (cin >> n&&n){
nameToId.clear();
string s;
cin >> s;
amount = 0;
getId(s);
string s1, s2;
vector<int> son[210];
for (int i = 1; i < n; i++){
cin >> s1 >> s2;
int id1 = getId(s1), id2 = getId(s2);
son[id2].push_back(id1);
}
cout << max(dp(son, 0, 0), dp(son, 0, 1));
if (judge(0)) cout << " Yes" << endl;
else cout << " No" << endl;
}
return 0;
}