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.
Source |
介个题好套路 ,处理那个方向输入时,要记得前面加一个空格。
用树的直径就可以求,但是不理解啊。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 40005;
vector<int> son[maxn], w[maxn];
bool vis[maxn], viss[maxn];
int f[maxn];
int bfs(int root){
int i, j, k;
int ans = root, maxx = 0;
queue<int> q;
memset(vis,0,sizeof(vis));
memset(f,0,sizeof(f));
q.push(root);
vis[root] = 1;f[root] = 0;viss[root] = 1;
while(!q.empty()){
root = q.front();
q.pop();
for(i=0;i<son[root].size();i++){
if(vis[son[root][i]]==0){
q.push(son[root][i]);
vis[son[root][i]] = 1;viss[son[root][i]] = 1;
f[son[root][i]] = f[root]+w[root][i];
if(maxx<f[son[root][i]]){
maxx = f[son[root][i]];
ans = son[root][i];
}
}
}
}
return ans;
}
int solve(int root){
int u, v;
u = bfs(root);
v = bfs(u);
return f[v];
}
int main(){
int i, j, k, n, m;
int x1, x2, l, u;
int res;
char opt;
while(~scanf("%d%d",&n,&m)){
for(i=0;i<=n;i++){
son[i].clear();
w[i].clear();
}
for(i=0;i<m;i++){
scanf("%d%d%d",&x1,&x2,&l);
scanf(" %c",&opt);
son[x1].push_back(x2);w[x1].push_back(l);
son[x2].push_back(x1);w[x2].push_back(l);
}
res = 0;
memset(viss,0,sizeof(vis));
for(i=1;i<=n;i++){
if(viss[i]==0){
res = max(res,solve(i));
}
}
printf("%d\n",res);
}
return 0;
}