POJ1985 Cow Marathon樹的直徑
http://poj.org/problem?id=1985
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.
#include<iostream> #define MAXN 1010000 #include<vector> #include<cstdio> #include<string.h> using namespace std; struct Edge { int v,w; Edge(int vv,int ww):v(vv),w(ww) {} }; int n,m; int dist[MAXN],max_len,End; vector<vector<Edge> >G; void dfs(int u,int father,int len) { //起點,父親節點,兩者之間長度 if(len>max_len)max_len=len,End=u;//更新終點; for(int i=0; i<G[u].size(); i++) { //對於每一個節點,進行深搜; int v=G[u][i].v,w=G[u][i].w;//與之相連的點; if(v==father)continue; dist[v]=max(dist[v],len+w);//更新到子節點之間的最大距離; dfs(v,u,len+w);//繼續深搜; } } int main() { int u,v,w; char ch; cin>>n>>m; G.clear();//清空 G.resize(n+2);//申請空間 for(int i=1; i<=m; i++) { scanf("%d%d%d %c",&u,&v,&w,&ch); G[u].push_back(Edge(v,w)); G[v].push_back(Edge(u,w)); //無向圖; } memset(dist,0,sizeof(dist)); max_len=0; dfs(1,-1,0);//第一次深搜找到距離某點最遠的點op dfs(End,-1,0);//求距離op最遠的點,兩次深搜求出直徑; int ans=0; cout<<dist[End]<<endl; return 0; }
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define MOD 100000000
#define inf 2147483640
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;
const int maxn=40010;
struct edge {int to,next,w;}e[maxn<<1];
int n,m,rt,ans,cnt,head[maxn];
void link(int u,int v,int w) {
e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w;
e[++cnt].to=u;e[cnt].next=head[v];head[v]=cnt;e[cnt].w=w;
}
void dfs(int x,int fa,int d) {
if (ans<d) ans=d,rt=x;
for (int i=head[x];i;i=e[i].next)
if (e[i].to!=fa) dfs(e[i].to,x,d+e[i].w);
}
int main() {
scanf("%d%d",&n,&m);
char ch;
for (int u,v,w,i=1;i<=m;i++) {
scanf("%d%d%d %c",&u,&v,&w,&ch);
link(u,v,w);
}
rt=ans=0;dfs(1,0,0);
dfs(rt,0,0);
printf("%d",ans);
return 0;
}