Description
After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
Input
* Lines 1.....: Same input format as "Navigation Nightmare".
Output
* Line 1: An integer giving the distance between the farthest pair of farms.
Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S
Sample Output
52
树的直径问题:两次dfs
证明:
树的直径是指树的最长简单路。求法: 两遍BFS :先任选一个起点BFS找到最长路的终点,再从终点进行BFS,则第二次BFS找到的最长路即为树的直径;
原理: 设起点为u,第一次BFS找到的终点v一定是树的直径的一个端点
证明: 1) 如果u 是直径上的点,则v显然是直径的终点(因为如果v不是的话,则必定存在另一个点w使得u到w的距离更长,则于BFS找到了v矛盾)
2) 如果u不是直径上的点,则u到v必然于树的直径相交(反证),那么交点到v 必然就是直径的后半段了
所以v一定是直径的一个端点,所以从v进行BFS得到的一定是直径长度
转自:http://www.cppblog.com/jie414341055/archive/2010/07/08/119662.html
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int MAX=100000;
struct node //邻接表
{
int to,w;
int next;
}e[MAX];
int Max,k;
bool vis[MAX];
int head[MAX]; //表头
void dfs(int u,int len,bool vis[])
{
if(len>Max)
{
Max=len;
k=u;
}
for (int i=head[u]; i!=-1; i=e[i].next)
{
if(!vis[e[i].to])
{
vis[e[i].to]=true;
dfs(e[i].to,len+e[i].w, vis);
vis[e[i].to]=false;
}
}
}
int main()
{
int n,m;
while (scanf("%d%d",&n,&m)!=EOF)
{
int a,b,w;
char ch;
for (int i=1; i<=n; i++)
{
head[i]=-1;
}
int j=0;
memset(vis, false, sizeof(vis));
while(m--)
{
scanf("%d%d%d %c",&a,&b,&w,&ch);
e[j].to=b;
e[j].w=w;
e[j].next=head[a];
head[a]=j;
j++;
e[j].to=a;
e[j].w=w;
e[j].next=head[b];
head[b]=j;
j++;
}
Max=-1;
for (int i=0; i<=n; i++)
{
vis[i]=false;
}
vis[1]=true;
dfs(1,0, vis);
for (int i=0; i<=n; i++)
{
vis[i]=false;
}
vis[k]=true;
Max=-1;
dfs(k, 0, vis);
printf("%d\n",Max);
}
return 0;
}