[UVA][樹型DP] 10308 - Roads in the North
Problem I
Roads in the North
Input: standard input
Output: standard output
Time Limit: 2 seconds
Memory Limit: 32 MB
Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are built in such a way that there is only one route from a village to a village that does not pass through some other village twice.
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area.
The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.
Input
The input contains several sets of input. Each set of input is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way. Two consecutive sets are separated by a blank line.
Output
For each set of input, you are to output a single line containing a single integer: the road distance between the two most remote villages in the area.
Sample Input
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
Sample Output
22
原本沒有權重的最長路徑,作法如下
做法 : 兩次 dfs,
1st dfs :
得到由下而上的最大高度 (要記錄第一高 第二高),
意即 得到每個節點的 subtree 的高度
2nd dfs :
將父節點高度轉過來, 這時要注意, 如果第一高是從這個節點接上去的, 那麼就抓第二高+1,
接著我們將 +1 的部分改成連接起來的 weight 值即可。
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
struct ele {
int to, v;
};
vector<ele> g[10001];
int dp1[10001][2], dp2[10001];
void init() {
static int i;
for(i = 1; i <= 10000; i++)
g[i].clear(), dp1[i][0] = dp1[i][1] = dp2[i] = 0;
}
void dfs1(int nd, int p) {
for(vector<ele>::iterator it = g[nd].begin();
it != g[nd].end(); it++) {
if(it->to != p) {
dfs1(it->to, nd);
if(dp1[it->to][0] + it->v > dp1[nd][1])
dp1[nd][1] = dp1[it->to][0] + it->v;
if(dp1[nd][1] > dp1[nd][0])
swap(dp1[nd][0], dp1[nd][1]);
}
}
}
void dfs2(int nd, int p, int st, int w) {
if(nd != st) {
if(dp1[nd][0] + w == dp1[p][0])
dp2[nd] = max(dp2[p], dp1[p][1])+w;
else
dp2[nd] = max(dp2[p], dp1[p][0])+w;
}
for(vector<ele>::iterator it = g[nd].begin();
it != g[nd].end(); it++) {
if(it->to != p) {
dfs2(it->to, nd, st, it->v);
}
}
}
void sol(int st) {
dfs1(st, -1);
dfs2(st, -1, st, 0);
int ans = 0, i;
for(i = 1; i <= 10000; i++) {
ans = max(ans, dp1[i][0]+dp1[i][1]);
ans = max(ans, dp1[i][0]+dp2[i]);
}
printf("%d\n", ans);
}
int main() {
char cmd[100];
ele E;
int x, y, v;
while(gets(cmd)) {
if(cmd[0] == '\0') {
sol(x);
init();
continue;
}
sscanf(cmd, "%d %d %d", &x, &y, &v);
E.to = x, E.v = v;
g[y].push_back(E);
E.to = y;
g[x].push_back(E);
}
sol(x);
return 0;
}