原题:
Cow Marathon
Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 7641 Accepted: 3612
Case Time Limit: 1000MS
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
USACO 2004 February
中文:
给你一颗树让你找出这棵树的直径
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
const int N=50005;
vector<int> G[N];
map<pair<int,int>,int> mp;
int f1[N],f2[N];
int ans;
void dp(int x,int fa)
{
for(int i=0;i<G[x].size();i++)
{
if(G[x][i]==fa)
continue;
dp(G[x][i],x);
int w = mp[make_pair(x,G[x][i])];
if(f1[x]<f1[G[x][i]]+w)
{
f2[x]=f1[x];
f1[x]=f1[G[x][i]]+w;
}
else
{
if(f2[x]<f1[G[x][i]]+w)
f2[x]=f1[G[x][i]]+w;
}
ans=max(ans,f1[x]+f2[x]);
}
}
int main()
{
ios::sync_with_stdio(false);
int a,b,c;
char C;
int n,m;
while(cin>>n>>m)
{
memset(f1,0,sizeof(f1));
memset(f2,0,sizeof(f2));
mp.clear();
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c>>C;
G[a].push_back(b);
G[b].push_back(a);
mp[make_pair(a,b)]=c;
mp[make_pair(b,a)]=c;
}
ans=0;
dp(1,0);
cout<<ans<<endl;
}
return 0;
}
解答:
计算树的直径的裸题,和poj2631的解法一样