1. 程式人生 > >2017.10.12. DFS求樹的直徑

2017.10.12. DFS求樹的直徑

DFS求樹的直徑

適用題型:
1.求樹的直徑
2.求數的最長璉

樣題:

Cow Marathon【樹的直徑模板】
題目背景
POJ1985

題目描述
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.

輸入格式
* 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.

輸出格式
* Line 1: An integer giving the distance between the farthest pair of farms.

樣例資料 1
輸入  [複製]

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
輸出

52
備註
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.

std.cpp:

#include<cstdio>
#include<cstdlib> #include<iostream> #include<iomanip> #include<cstring> #include<string> #include<algorithm> #include<ctime> using namespace std; const int kkk = 1000050; int n,k,x,u,v,val; int first[kkk]; struct node{int u,v,val,next;}side[2*kkk]; int cnt=0; void addedge(int u,int v,int val) { side[++cnt].u = u; side[cnt].v = v; side[cnt].val = val; side[cnt].next = first[u]; first[u] = cnt; } bool visit[kkk]; int head=0,tail=0; int p[kkk],dis[kkk]; int s1,t1,s[kkk],t[kkk]; void spfa() { memset(visit,0,sizeof(visit)); memset(dis,127,sizeof(dis)); for(int i=1;i<=s1;i++) { dis[s[i]]=0; p[++tail]=s[i]; visit[s[i]]=true; } while(head<tail) { head++; visit[p[head]]=false; for(int i=first[p[head]];i;i=side[i].next) { u = side[i].u; v = side[i].v; if(dis[v]>dis[u]+side[i].val) { dis[v] = dis[u]+side[i].val; if(!visit[v]) { tail++; p[tail]=v; visit[v]=true; } } } } } int main() //主程式,SPFA { cin >> n >> k; for(int i=1;i<=k;i++) { char c; cin >> u >> v >> val >> c; addedge(u,v,val); addedge(v,u,val); } s1=1; s[1]=1; spfa(); int jud=0; for(int i=1;i<=n;i++)if(dis[i]>jud) s[1]=i,jud=dis[i]; spfa(); int ans=0; for(int i=1;i<=n;i++)ans=max(ans,dis[i]); cout << ans << endl; return 0; }