B - Cow Marathon DFS+vector存图
Posted accepting
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了B - Cow Marathon DFS+vector存图相关的知识,希望对你有一定的参考价值。
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条路,以及每条路的方向(方向在这道题中没有用),求最长的一条路,也就是两点间的最大距离,即树的直径.
有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存图的主要内容,如果未能解决你的问题,请参考以下文章