问题描述:
给出图来,让你算出树的最大直径即两点之间最长的距离。
原题描述:
Description
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.
Output
For each case, print the case number and the maximum distance.
Sample Input
2
4
0 1 20
1 2 30
2 3 50
5
0 2 20
2 1 10
0 3 29
0 4 50
Sample Output
Case 1: 100
Case 2: 80
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<set>
using namespace std;
#define X first
#define Y second
const int INF = 0x3f3f3f3f;
const int MAX = 3e4 + 10;
int head[MAX];
int ans, top;
struct node{
int to, w, next;
}edge[MAX<<1];
void add_edge(int u, int v, int w)
{
edge[top].to = v;
edge[top].w = w;
edge[top].next = head[u];
head[u] = top++;
}
void init(){
ans = top = 0;
memset(head, -1, sizeof(head));
}
int dfs(int pos1, int pos2){
int sum = 0, sum1 = 0;
for(int i = head[pos1]; i != -1; i = edge[i].next){
int to = edge[i].to;
int w = edge[i].w;
if(to == pos2) continue;
int temp = w + dfs(to, pos1);//先找出所有分支然后回溯时找到最长的分支相加
if(temp > sum){
sum1 = sum;
sum = temp;
}else if(temp > sum1){
sum1 = temp;
}
}
if(sum + sum1 > ans)
ans = sum + sum1;
return sum;
}
int main(){
int t, cns = 1;
scanf("%d", &t);
while(t--){
init();
int n;
scanf("%d", &n);
int u, v, w;
for(int i = 1; i < n; i++){
scanf("%d%d%d", &u, &v, &w);
add_edge(u, v, w);
add_edge(v, u, w);
}
dfs(0, -1);
printf("Case %d: %d\n", cns++, ans);
}
return 0;
}