Give you a tree, ask you to find the length of the diameter of the tree
Idea: Just find a point bfs out the longest point, that point must be a diameter starting point, and then from that point BFs out the longest point can be
The following study for half a day to dare to hand over, 1. The input format of the problem follows poj1984, in fact, it is to ignore the following letter 2. The amount of data is not given, so the array opened very big to dare to pay tut
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <queue>
#define MAXN 120090
#define ESP 0.00001
#define INF 0x3f3f3f3f
using namespace Std;
int HEAD[MAXN],VALUE[MAXN],NEXT[MAXN],POINT[MAXN];
int Now=0,dist[maxn],x,y,v,ans;
void Add (int x,int Y,int v)
{
NEXT[++NOW]=HEAD[X];
Head[x]=now;
Point[now]=y;
Value[now]=v;
}
int BFS (int s)
{
queue<int>q;
Q.push (s);
memset (dist,-1,sizeof (Dist));
dist[s]=0;
int maxx=0,maxj=-1;
while (!q.empty ())
{
int U=q.front ();
Q.pop ();
for (int i=head[u];i;i=next[i])
{
int k=point[i];
if (dist[k]==-1)
{
Dist[k]=dist[u]+value[i];
if (Dist[k]>maxx)
{
MAXX=DIST[K];
Maxj=k;
}
Q.push (k);
}
}
}
Ans=maxx;
return MAXJ;
}
int main ()
{
int n,m;
Char ch[10];
scanf ("%d%d", &n,&m);
for (int i=1;i<=m;i++)
{
scanf ("%d%d%d%s", &x,&y,&v,ch);
Add (X,Y,V);
Add (Y,X,V);
}
int U=bfs (1);
ans=0;
BFS (U);
printf ("%d\n", ans);
return 0;
}
POJ 1985 Cow Marathon "diameter of the tree"