您的位置:首页 > 其它

POJ 1985 Cow Marathon(树的直径)

2017-07-17 17:55 246 查看
Cow Marathon

Time Limit: 2000MSMemory Limit: 30000K
Total Submissions: 5357Accepted: 2630
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

先假设节点1是根节点,
跑到离他最远的点,
再从最远的点开始跑,
跑到的最远的的点就是树的直径

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define lli long long int
using namespace std;
const int MAXN=100001;
void read(int &n)
{
char c='+';int x=0;bool flag=0;
while(c<'0'||c>'9'){c=getchar();if(c=='-')flag=1;}
while(c>='0'&&c<='9')
x=(x<<1)+(x<<3)+c-48,c=getchar();
flag==1?n=-x:n=x;
}
struct node
{
int u,v,w,nxt;
}edge[MAXN];
int head[MAXN];
int num=1;
int n,m;
void add_edge(int x,int y,int z)
{
edge[num].u=x;
edge[num].v=y;
edge[num].w=z;
edge[num].nxt=head[x];
head[x]=num++;
}
int dp[MAXN];
int ans=0;
int ed=0;
void dfs(int u,int fa,int now)
{
if(now>ans)
{
ans=now;
ed=u;
}
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
if(edge[i].v!=fa)
dfs(edge[i].v,u,now+edge[i].w);
}
}
int  main()
{
read(n);read(m);
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
int x,y,z;char c;
read(x);read(y);read(z);
cin>>c;
add_edge(x,y,z);
add_edge(y,x,z);
}
dfs(1,0,0);
dfs(ed,0,0);
printf("%d",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: