Description
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area.
The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.
Input
Output
Sample Input
5 1 6 1 4 5 6 3 9 2 6 8 6 1 7
Sample Output
22
-
#include<iostream>
#include<stdio.h>
#include <string.h>
#include<algorithm>
using namespace std;
#define maxe 20010
struct node
{
int v,w;
int next;
}Edge[maxe];
int head[maxe];
int len;
bool vis[maxe];
void add(int a,int b,int w)
{
Edge[len].v=b;
Edge[len].w=w;
Edge[len].next=head[a];
head[a]=len++;
}
int ans;
int temp;
void dfs(int u,int value)
{
if(ans<value)
{
ans=value;
temp=u;
}
vis[u]=true;
for (int i=head[u]; i!=-1; i=Edge[i].next)
{
int v=Edge[i].v;
if(!vis[v])
{
dfs(v, value+Edge[i].w);
}
}
}
int main()
{
int u,v,w;
len=0;
memset(head, -1,sizeof(head));
while(scanf("%d%d%d",&u,&v,&w)!=EOF)
{
add(u,v,w);
add(v,u,w);
}
ans=0;
memset(vis,false, sizeof(vis));
dfs(1,0);
ans=0;
memset(vis,false, sizeof(vis));
dfs(temp,0);
printf("%d\n",ans);
return 0;
}