码迷,mamicode.com
首页 > 其他好文 > 详细

B - Cow Marathon DFS+vector存图

时间:2019-07-25 13:26:22      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:step   scan   set   pre   direct   ide   路径   dem   get   

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. 
有n个农田和m条路,以及每条路的方向(方向在这道题中没有用),求最长的一条路,也就是两点间的最大距离,即树的直径.

Input

* Line 1: Two space-separated integers: N and M


* Lines 2..M+1: Each line contains four space-separated entities, F1,
F2, L, and D that describe a road. F1 and F2 are numbers of
two farms connected by a road, L is its length, and D is a
character that is either ‘N‘, ‘E‘, ‘S‘, or ‘W‘ giving the
direction of the road from F1 to F2.

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

题目大意:从点A到点B的距离是C,有N个点,M条线,问两点之间最远的距离;
思路:
首先按要存图,一开开始是用的数组,一直RE后来才发现数的范围是1E5,二维数组直接就蹦了,所以要用Vector存图,输入的时候也要用c语言的常规输入输出,不然会TLE

#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
int n,m;//m个农场,6条路径 
struct stu{
    int a,b;//保存点2和点1 到点2点距离
}e;

vector<stu >arr[100100];
int mark[100010];//标记数组
int ans=0;
int xx;

void dfs(int x,int step){
    if(step>ans){
        ans=step;
        xx=x;
    }
    for(int i=0;i<arr[x].size();i++){//arr[x]中的点肯定是与x相连接的点
        if(mark[arr[x][i].a]==0){
            mark[arr[x][i].a]=1;
            dfs(arr[x][i].a,step+arr[x][i].b);
            mark[arr[x][i].a]=0;
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    int x,y,z;
    char s;
    memset(arr,0,sizeof(arr));
    for(int i=0;i<m;i++){
//        scanf("%d%d%d %c\n",&x,&y,&z);
//        cin>>x>>y>>z>>s;
        scanf("%d %d %d",&x,&y,&z);
        getchar(), getchar();
//        getchar();
//        getchar();getchar();
        arr[x].push_back({y,z});
        arr[y].push_back({x,z});
//        arr[x][y]=z;
//        arr[y][x]=z;
        
    }
    
    ans=0;
    memset(mark,0,sizeof(mark));
    mark[1]=1;
    dfs(1,0);
    memset(mark,0,sizeof(mark));
    mark[xx]=1;
    dfs(xx,0);//两轮dfs直接输出
    cout<<ans<<endl;
    return 0;
}

 




B - Cow Marathon DFS+vector存图

标签:step   scan   set   pre   direct   ide   路径   dem   get   

原文地址:https://www.cnblogs.com/Accepting/p/11243635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!