poj3342 Party at Hali-Bula

树形dp题,状态转移方程应该很好推,但一定要细心。

http://poj.org/problem?id=3342

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
const int maxn = + ;
char buf[maxn];
struct Edge{
int to, next;
}edge[maxn << ];
int head[maxn], N;
map<string, int> mapi;
int n, k;
int dp[maxn][];
int o[maxn][];
int get_str(char *dest){
int cnt = ;
char ch;
do{
ch = getchar();
}while(ch != EOF && (ch == ' ' || ch == '\n'));
if(ch == EOF) return ;
dest[cnt++] = ch;
while((ch = getchar()) != ' ' && ch != '\n' && ch != EOF) dest[cnt++] = ch;
dest[cnt] = '\0';
return cnt;
} void addEdge(int u, int v){
edge[N].next = head[u];
edge[N].to = v;
head[u] = N++;
} void dfs(int u, int fa){
dp[u][] = ;
int tem1 = , tem2 = ;
for(int i = head[u]; i + ; i = edge[i].next){
int v = edge[i].to;
if(v == fa) continue;
dfs(v, u);
dp[u][] += dp[v][];
o[u][] |= o[v][];
int d = dp[v][] > dp[v][] ? : (dp[v][] == dp[v][] ? - : );
if(d == -){
dp[u][] += dp[v][];
o[u][] = ;
}else{
dp[u][] += dp[v][d];
o[u][] |= o[v][d];
}
}
} int main(){
//freopen("in.txt", "r", stdin);
while(~scanf("%d", &n) && n){
k = ;
int base = ;
get_str(buf);
mapi.clear();
mapi[string(buf)] = ++base;
N = ;
memset(head, -, sizeof head);
for(int i = , x, y; i < n; i++){
get_str(buf);
if(mapi.find(string(buf)) == mapi.end()) mapi[string(buf)] = ++base, x = base;
else x = mapi[string(buf)];
get_str(buf);
if(mapi.find(string(buf)) == mapi.end()) mapi[string(buf)] = ++base, y = base;
else y = mapi[string(buf)];
addEdge(x, y);
addEdge(y, x);
}
memset(dp, , sizeof dp);
memset(o, , sizeof o);
dfs(, );
int ans = -;
bool ok = ;
for(int i = ; i <= n; i++) for(int j = ; j <= ; j++){
if(dp[i][j] > ans) ans = dp[i][j], ok = o[i][j];
else if(dp[i][j] == ans) ok = ;
}
printf("%d %s\n", ans, ok ? "No" : "Yes");
}
return ;
}
上一篇:Rsync文件同步


下一篇:设计模式之美:Role Object(角色对象)