树的直径

本文介绍了一种求解树上最长简单路径(即树的直径)的方法,通过两次深度优先搜索找到两个最远节点间的距离。同时提供了一个具体的示例程序,展示了如何使用这种方法来解决实际问题。

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

解决办法

  一开始任取一个点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\n",inf);
    return 0;
}

 

转载于:https://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/9306605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值