树的直径

树上面最长简单路(无环),就是树的直径问题

解决办法

  一开始任取一个点u进行搜索查找出距离点u最远距离的点v和长度

  第二次dfs则从第一次中的v找出距离点v最远距离的点的路径长度

Cow Marathon

 

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
树的直径裸题
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
struct node
{
    int to,val,next;
}e[10000000];
int n,m,x,y,w,pos;
int vis[100005],dis[100005],head[100005];
void add(int u,int v,int val)
{
    e[pos].to=v;
    e[pos].val=val;
    e[pos].next=head[u];
    head[u]=pos++;
}
void dfs(int f,int u,int d)
{
    dis[u]=d;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        if(e[i].to!=f)
            dfs(u,e[i].to,d+e[i].val);
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    char s[10];
    memset(head,-1,sizeof(head));
    for(int i=0;i<m;i++)
    {
        scanf("%d%d%d",&x,&y,&w);
        add(x,y,w);
        add(y,x,w);
    }
    dfs(0,1,0);
    int inf=-1,pos;
    for(int i=1;i<=n;i++)
        if(dis[i]>inf)inf=dis[i],pos=i;
    dfs(0,pos,0);
    for(int i=1;i<=n;i++)
        inf=max(inf,dis[i]);
    printf("%d
",inf);
    return 0;
}
原文地址:https://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/9306605.html