POJ 1985 Cow Marathon(求树的直径)

POJ 1985 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

Hint

The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.

题意

n个节点,m条路径(无向边)。求图中两点的最大长度。题目中虽然两点时间还有位置的方向,但是,因为两点之间的距离还是要沿着边走,所以可以忽略给出边中两点的方向关系。
另外。。。这个题没给数据范围。

思路

求树的最大直径。先选任意一个点为起点,用dfs求其他点到起点的距离。再把到起点最远的点设为起点,初始化距离后再次dfs求到其他点的距离,其中最远的距离就是这颗树的最大直径。
原因:第一次dfs的最远点一定是这颗树最大直径上的一个端点。故,再次dfs后找到的最远的点就是另一个端点。两个端点的距离就是最大长度

AC代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
using namespace std;
#define inf 0x3f3f3f3f
const int N=1e5+10;
vector<int>v[N],vv[N];  //用了两个vector,v[i]用来存节点的对应关系,vv用来表示相应点的长度
bool vis[N];  //标记是否访问
int dis[N];  //dis[i]为出发点到节点i的距离
void add(int a,int b,int c)  //双向加边以及两点之间的距离
{
    v[a].push_back(b);
    vv[a].push_back(c);
    v[b].push_back(a);
    vv[b].push_back(c);
}
void dfs(int a)  //dfs求距离
{
    vis[a]=1;
    int i,b,m=v[a].size();
    for(i=0;i<m;i++){
        b=v[a][i];
        if(!vis[b]){
            dis[b]=dis[a]+vv[a][i];
            dfs(b);
        }
    }
}
int main()
{
    int n,m;
    int i,a,b,c;
    char s[10];
    scanf("%d %d",&n,&m);
    for(i=1;i<=m;i++){
        scanf("%d %d %d %s",&a,&b,&c,s);
        add(a,b,c);
    }
    memset(vis,0,sizeof(vis));
    dis[1]=0;  //初始化距离
    for(i=2;i<=n;i++)
        dis[i]=inf;
    dfs(1);  //假设1号节点为出发点
    int mm=-1;
    int start=1;
    for(i=1;i<=n;i++){
        if(dis[i]>mm&&dis[i]!=inf){
            mm=dis[i];
            start=i;  //更新下次的出发点
        }
    }
    memset(vis,0,sizeof(vis));
    for(i=1;i<=n;i++){  //初始化距离
        dis[i]=(i==start?0:inf);
    }
    dfs(start);  //第二次dfs
    int ans=-1;
    for(i=1;i<=n;i++){
        if(dis[i]>ans&&dis[i]!=inf){
            ans=dis[i];  //更新最大距离
        }
    }
    printf("%d\n",ans);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值