Roads in the North
Description Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice. Input Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way. Output You are to output a single integer: the road distance between the two most remote villages in the area. Sample Input Sample Output Source |
[Submit] [Go Back] [Status] [Discuss]
树的直径模版题,直接上板子就行了。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int MAXN=100010;
int len,point,top;//记录直径,最远点
struct node{
int to,next,w;
}edge[MAXN];
int dis[MAXN];//记录距离
bool vis[MAXN];
int head[MAXN];
void addEdge(int u,int v,int z){
edge[top].to=v;
edge[top].w=z;
edge[top].next=head[u];
head[u]=top++;
}
void BFS(int s){
queue<int> qu;
memset(dis,0,sizeof(dis));
vis[s]=1;
qu.push(s);
while(!qu.empty()){
int x=qu.front();qu.pop();
for(int i=head[x];i!=-1;i=edge[i].next){
int y=edge[i].to;
if(!vis[y]){
dis[y]=dis[x]+edge[i].w;
if(len<dis[y]){
len=dis[y];
point=y;
}
vis[y]=1;
qu.push(y);
}
}
}
}
int main(){
int x,y,z;
//memset(vis,0,sizeof(vis));
memset(head,-1,sizeof(head));
top=0;
while(~scanf("%d%d%d",&x,&y,&z)){
addEdge(x,y,z);
addEdge(y,x,z);
}
len=0;
memset(vis,0,sizeof(vis));
BFS(1);//找出最远点
len=0;
memset(vis,0,sizeof(vis));
BFS(point);
printf("%d\n",len);
return 0;
}