lightoj1094Farthest Nodes in a Tree

来源:互联网 发布:淘宝店铺处置期 编辑:程序博客网 时间:2024/06/05 03:34
Farthest Nodes in a Tree
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu
Submit Status

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<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAX=30000+10;
const int MAXN=2*30000+10;
struct Edge{
int from,to,val,next;
}edge[MAXN];
int dist[MAX];
int vis[MAX];
int head[MAX];
int top,ans,node;
void init()
{
top=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int w)
{
Edge E={u,v,w,head[u]};
edge[top]=E;
head[u]=top++;
}
void bfs(int sx)
{
queue<int>q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
node=sx;
ans=0;
vis[sx]=1;
q.push(sx);
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i!=-1;i=edge[i].next)
{
Edge E=edge[i];
if(!vis[E.to])
{
dist[E.to]=dist[u]+E.val;
if(ans<dist[E.to])
{
ans=dist[E.to];
node=E.to;
}
vis[E.to]=1;
q.push(E.to);
}
}
}
}
int main()
{
int t,n,a,b,c;
scanf("%d",&t);
int l=1;
while(t--)
{
init();
scanf("%d",&n);
n--;
while(n--)
{
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
addedge(b,a,c);
}
bfs(1);
bfs(node);
printf("Case %d: %d\n",l++,ans);
}
return 0;
}


0 0