1094 - Farthest Nodes in a Tree
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<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#define maxn 30030
using namespace std;
struct Edge
{
int v,w;
};
vector<Edge>edge[maxn];
int rec,ans;
void bfs(int s)
{
bool vis[maxn];
int dis[maxn];
memset(vis,false,sizeof(vis));
memset(dis,0,sizeof(dis));
vis[s]=true;
queue<int>q;
q.push(s);
rec=s;
ans=0;
while(!q.empty())
{
int u=q.front();
q.pop();
int len=edge[u].size();
for(int i=0;i<len;++i)
{
int v=edge[u][i].v;
if(!vis[v]&&dis[v]<dis[u]+edge[u][i].w)
{
dis[v]=dis[u]+edge[u][i].w;
if(dis[v]>ans)
{
ans=dis[v];
rec=v;
}
vis[v]=true;
q.push(v);
}
}
}
}
int main()
{
int t,n,u,v,w,num=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<n;++i)
{
scanf("%d%d%d",&u,&v,&w);
edge[u].push_back(Edge{v,w});
edge[v].push_back(Edge{u,w});
}
bfs(0);
bfs(rec);
printf("Case %d: %d\n",++num,ans);
for(int i=0;i<n;++i)
edge[i].clear();
}
return 0;
}