UVA - 1220 Party at Hali-Bula 树形DP入门

UVA - 1220 

昨天心情不好 因为两道DP题坑了~ 比较奇特的是这题对我来说却相当好理解。。第一次写对状态转移方程。。。难道是因为在树上。。。= = 不知道。好吧 反正就是 树的最大独立集问题,选尽量多的人,但不能同时选一个人和他的上司,想象一下这种结构,如果是有两层的树,要么选根,要么选叶子,对吧,也就是对每个节点(每个人)来说,都有两种决策,选或者不选,如果选这个人,那么所有的叶子都不能选,如果不选,所有的叶子都有两种决策。这样就比较清晰了,关于唯一性的问题,如果选这个人,当且仅当他的叶子都唯一时,该点得到的值唯一;不选时,如果叶子选与不选得到的结果相同,那一定是不唯一的,选了叶子的最大值,该点的唯一性也就是叶子状态对应的唯一性。、

由于现在VJ崩了找不到我的代码了 就先不贴了 贴一份lrj老先生的吧,有助于理解我说的啥。。

#include <cstdio>
#include <cmath>
#include <map>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <iostream>
#include <utility>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 205;
int n,d[maxn][2],f[maxn][2],cnt;
string s1,s2;
vector<int > sons[maxn];
map<string, int> dict;
int ID(const string& s) {
  if(!dict.count(s)) dict[s] = cnt++;
  return dict[s];
}
int dp(int x, int c) {
  f[x][c] = 1;
  d[x][c] = c;
  for(int i = 0; i < sons[x].size(); i++) {
    int v = sons[x][i];
    if(c == 1) {
      d[x][1] += dp(v, 0);
      if(!f[v][0]) f[x][1] = 0;
    } else {
            d[x][0] += max(dp(v, 0), dp(v, 1));
            if(d[v][0] == d[v][1]) f[x][c] = 0;
            else if(d[v][0] > d[v][1] && !f[v][0]) f[x][c] = 0;
            else if(d[v][1] > d[v][0] && !f[v][1]) f[x][c] = 0;
    }
  }
  return d[x][c];
}
int main() {
  string s, s2;
  while(cin >> n >> s) {
    cnt = 0;
    dict.clear();
    for(int i = 0; i < n; i++) sons[i].clear();

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值