lght oj 1257 - Farthest Nodes in a Tree (II) (树dp)

题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1257

hdu2196一样,两次dfs

 //#pragma comment(linker, "/STACK:102400000, 102400000")
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
typedef pair <int, int> P;
const int N = 1e5 + ;
struct Edge {
int next, to, cost;
}edge[N << ];
int head[N], tot;
P d[N], pos[N];
int up[N]; void init(int n) {
memset(head, -, sizeof(head));
tot = ;
for(int i = ; i <= n; ++i) {
d[i].first = d[i].second = ;
pos[i].first = pos[i].second = -;
up[i] = ;
}
} inline void add(int u, int v, int cost) {
edge[tot].next = head[u];
edge[tot].to = v;
edge[tot].cost = cost;
head[u] = tot++;
} void dfs1(int u, int p) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if(v == p)
continue;
dfs1(v, u);
if(d[v].first + edge[i].cost > d[u].first) {
if(d[u].first != )
d[u].second = d[u].first;
d[u].first = d[v].first + edge[i].cost;
pos[u].first = v;
} else if(d[v].first + edge[i].cost > d[u].second) {
d[u].second = d[v].first + edge[i].cost;
pos[u].second = v;
}
}
} void dfs2(int u, int p) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if(v == p)
continue;
if(v == pos[u].first) {
up[v] = max(up[u], d[u].second) + edge[i].cost;
} else {
up[v] = max(up[u], d[u].first) + edge[i].cost;
}
dfs2(v, u);
}
} int main()
{
int t, n;
scanf("%d", &t);
for(int ca = ; ca <= t; ++ca) {
scanf("%d", &n);
init(n);
int u, v, cost;
for(int i = ; i < n; ++i) {
scanf("%d %d %d", &u, &v, &cost);
add(u, v, cost);
add(v, u, cost);
}
dfs1(, -);
dfs2(, -);
printf("Case %d:\n", ca);
for(int i = ; i < n; ++i) {
printf("%d\n", max(d[i].first, up[i]));
}
}
return ;
}
上一篇:Pytorch多GPU并行处理


下一篇:linux epoll 简单demo