POJ 1985 Cow Marathon(求树的直径)

版权声明:本文为博主原创文章,未经博主允许不得转载。若有误,欢迎私信指教~ https://blog.csdn.net/little_starfish/article/details/81778026

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;
}

猜你喜欢

转载自blog.csdn.net/little_starfish/article/details/81778026