DFS 搜索下经过每个点的最大长度就行。。。。
AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef struct{
int to;
int weight;
int next;
}Edge;
int head[40010], tot;
Edge edge[70010];
int N;
int max_distance;
void add_edge( int a, int b, int weight ){
edge[tot].to = b;
edge[tot].weight = weight;
edge[tot].next = head[a];
head[a] = tot++;
edge[tot].to = a;
edge[tot].weight = weight;
edge[tot].next = head[b];
head[b] = tot++;
}
int DFS( int pos, int pre ){
int first_max, second_max;
first_max = second_max = 0;
for( int i = head[pos]; i != -1; i = edge[i].next ){
int to = edge[i].to;
if( to == pre ){
continue;
}
int temp_dis = edge[i].weight + DFS( to, pos );
if( temp_dis > first_max ){//注意要更新这个second_max!!!
second_max = first_max;
first_max = temp_dis;
}else if( temp_dis > second_max ){
second_max = temp_dis;
}
}
if( first_max + second_max > max_distance ){
max_distance = first_max + second_max;
}
return first_max;
}
int main(){
int T, Case = 1;
scanf( "%d", &T );
while( T-- ){
memset( head, -1, sizeof( head ) );
tot = 0;
scanf( "%d", &N );
int temp1, temp2, temp3;
for( int i = 1; i < N; i++ ){
scanf( "%d%d%d", &temp1, &temp2, &temp3 );
add_edge( temp1, temp2, temp3 );
}
max_distance = 0;
DFS( 0, -1 );
cout << "Case " << Case++ << ": " << max_distance << endl;
}
return 0;
}