Uva1220

来源:互联网 发布:淘宝客服链接网址 编辑:程序博客网 时间:2024/06/07 12:17

题目链接

入门树形DP

思路:设d(u,0),f(u,0)是以u为根的子树中不选u点时能够得到的最大人数和表示方案唯一【f(u,0)表示方案唯一,f(u,1)表示方案不唯一】,d(u,1),f(u,1)表示选u点时能够得到的最大人数和表示方案唯一。

所以转移方程也有两种,一种是d(u,1)的计算,因为选了u点,所以u的直接子节点都不能选,因此d(u,1)=sum{d(v,0)|v是u的直接子节点不能选},当且仅当所有的f(v,0)=1时f(u,1)才是1【方案唯一】。另一种是d(u,0)的计算,因为u点没有被选择所以u的直接子节点可选或不选,即d(u,0)=sum{ max( d(v,0),d(v,1) ) }当d(v,0)=d(v,1)即选和不选子节点的情况一样则方案不唯一,当d(v,0)>d(v,1)且f(v,0)=0时方案不唯一,d(v,1)>d(v,0)且f(v,1)=0时方案也不唯一。

#include <iostream>#include <string>#include <set>#include <map>#include <stack>#include <vector>#include <iterator>#include <sstream>#include <algorithm>using namespace std;const int maxn = 210;map<string, int> Map;vector<int> v[maxn];int t, n, cnt;int f[maxn][maxn], d[maxn][maxn];string str, str1, str2;int ID(const string &s){    if (!Map.count(s))        Map[s] = cnt++;    return Map[s];  }int dp(int u, int k){    f[u][k] = 1;    d[u][k] = k;    for (int i = 0; i < v[u].size(); i++)    {        int vv = v[u][i];        if (k == 1)//当u点选时,数量为加上u直接子节点不选情况的数量        {            d[u][1] += dp(vv, 0);            if (!f[vv][0])                f[u][1] = 0;        }        else//当不选时        {            d[u][0] += max(dp(vv, 0), dp(vv, 1));            if (d[vv][0] == d[vv][1])                f[u][k] = 0;            else if (d[vv][0] > d[vv][1] && !f[vv][0])                f[u][k] = 0;            else if (d[vv][1] > d[vv][0] && !f[vv][1])                f[u][k] = 0;        }    }    return d[u][k];}int main() {    while (cin>>t>>str && t != 0)    {        cnt = 0;                Map.clear();        for (int i = 0; i < t; i++)            v[i].clear();        ID(str);        for (int i = 1; i < t; i++)        {            cin >> str1 >> str2;            v[ID(str2)].push_back(ID(str1));        }        int result = max(dp(0, 1), dp(0, 0));        cout << result << " ";        bool judge = false;         //判断方案是否唯一        if (d[0][1] > d[0][0] && f[0][1])            judge = true;        if (d[0][0] > d[0][1] && f[0][0])            judge = true;        if (judge)            cout << "Yes\n";        else            cout << "No\n";    }//  system("pause");    return 0;}
原创粉丝点击