Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 | Output for 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 | Case 1: 100 Case 2: 80 |
Notes
Dataset is huge, use faster i/o methods.
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int from,to,val,last;//last是该边所连接的上条边
}bian[60020];
int dis[30010];//标记某点到每点的距离
int head[30010];//标记每个点在哪条边出现,会更新,但是只要找到该点所在的某个边即可通过链表来找与它相连的边了
int vis[30010];//标记访问过的点
int n;
int num;
int start; //第一次搜索到最远的那个元素 (s点)
void add(int s,int e,int power)//标记某些数字出现在第几行,存到表头head中
{
bian[num].from=s;
bian[num].to=e;
bian[num].val=power;
bian[num].last=head[s];//如果它没有上条连接的边 就标记成-1 有的话就标记成上条变是第几条
head[s]=num;//更新下s所在的第几条边,num是边的号码
num++;
}
void bfs(int x)
{
int r=x;
queue<int>q;
q.push(r);
vis[r]=1;
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(int i=head[tmp];i!=-1;i=bian[i].last)
{
int tmp2=bian[i].to;
if(vis[tmp2]==0&&dis[tmp2]<dis[tmp]+bian[i].val)//找到当前边加哪个边后变长
{
dis[tmp2]=dis[tmp]+bian[i].val;
vis[tmp2]=1;
q.push(tmp2);
}
}
}
int max=0;
for(int i=0;i<n;i++)
{
if(dis[i]>max)
{
max=dis[i];
start=i;
}
}
}
int main()
{
int t;
scanf("%d",&t);
int hao=1;
while(t--)
{
memset(head,-1,sizeof(head));
scanf("%d",&n);
num=0;
for(int i=0;i<n-1;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);//求数的最大直径必须打双向的链表
add(y,x,z);
}
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
bfs(0);//随意找个点
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
bfs(start);
printf("Case %d: %d\n",hao++,dis[start]);
}
return 0;
}