题目链接:uva 1484 - Alice and Bob‘s Trip
题目大意:Alice和Bob小两口一起出去旅行,他们从0城市出发,Bob喜欢走比较远的路,因为他是个勤奋的好孩子,Alice喜欢走比较近的路,因为她是一个不勤奋的坏孩子,所以有了意见上的分歧,于是乎在出门前他们约法三章,要求说最后的距离值在[l,r]之间,并且由夫妻两轮流做决定,决定说下一个城市去哪里。现在给出n个城市,以及n-1条边,问说在不让Bob媳妇生气的情况下,Bob最远能走多远(不违反约定),如果无法做到不违反约定的话,输出Oh,my god!
解题思路:树形dp,其实有点像暴力,每个节点其实只会计算一次(树状结构,n-1条边,并且保证联通);
也就是说在题目给出图的时候,就已经确定说各个点所位于的层数,奇数层的肯定是Bob决定,偶数层的肯定是Alice决定。于是在每层计算的时候,有一个x值表示是奇数层还是偶数层,用于确定说是谁在做决定,如果是Bob,肯定选择最大的,如果是Alice肯定选择最小的,但是不管是谁,都要保证说不能违反约定,那么就不能将层与层之间完全分离计算距离,s为跟踪的距离值,用于判断是否违反约定。
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int N = 500005;
const int INF = 0x3f3f3f3f;
struct node {
int v, val;
node(int v = 0, int val = 0) {
this->v = v;
this->val = val;
}
};
vector<node> g[N];
int n, l, r;
void init () {
for (int i = 0; i < n; i++)
g[i].clear();
int a, b, c;
for (int i = 1; i < n; i++) {
scanf("%d%d%d", &a, &b, &c);
g[a].push_back(node(b, c));
}
}
int solve (int u, int x, int s) {
if (g[u].size() == 0)
return s;
int ans;
if (x) {
ans = INF;
for (int i = 0; i < g[u].size(); i++) {
int t = solve(g[u][i].v, 1-x, s+g[u][i].val);
if (t < l || t > r)
continue;
ans = min(ans, t);
}
} else {
ans = 0;
for (int i = 0; i < g[u].size(); i++) {
int t = solve(g[u][i].v, 1-x, s+g[u][i].val);
if (t < l || t > r)
continue;
ans = max(ans, t);
}
}
return ans;
}
int main () {
while (scanf("%d%d%d", &n, &l, &r) == 3) {
init();
int ans = solve(0, 0, 0);
if (ans >= l && ans <= r)
printf("%d\n", ans);
else
printf("Oh, my god!\n");
}
return 0;
}
uva 1484 - Alice and Bob's Trip(树形dp),布布扣,bubuko.com
uva 1484 - Alice and Bob's Trip(树形dp)
原文:http://blog.csdn.net/keshuai19940722/article/details/25040773