poj1985 Cow Marathon(树的直径#入门)
poj1985 Cow Marathon(樹的直徑)
Time Limit: 2000MS Memory Limit: 30000K Total Submissions: 9110 Accepted: 4171 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
Sample Output
52Hint
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
思路
先搞清樣例輸入:
from,to,val,direction(from到to有一條長val的邊,to在from的direction方向)
這里不用考慮方向,直接建雙向邊。
題意:求解兩個牧場之間最長的距離。
即求樹的直徑即可。
樹的直徑求解步驟:
pos1------pos2即為樹的直徑。
方法:
AC代碼:
- 法1:兩遍dfs(bfs略):
- 時間復雜度O(n)
- 優點:好記錄路徑
- 缺點:寫起來相對復雜一點點
簡化代碼:
#include <iostream> #include <cstring> #include <string> using namespace std; const int N = 1e5+5; struct Edge {int from;int to;int val;int nxt; } edge[N]; int head[N<<1],idx; void init() {memset(head,-1,sizeof(head));idx = 0; } inline void add_edge(int from,int to,int val) {edge[idx].from = from;edge[idx].to = to;edge[idx].val = val;edge[idx].nxt = head[from];head[from] = idx++; } int pos1,pos2,maxx; void dfs(int u,int fa,int dis) {if(dis > maxx){pos1 = u;maxx = dis;}for(int i = head[u]; ~i; i = edge[i].nxt){int to = edge[i].to;int val = edge[i].val;if(to != fa){dfs(to,u,dis+val);}} } int main() {int n,m;cin>>n>>m;int x,y,v;string d;init();while(m--){cin>>x>>y>>v>>d;add_edge(x,y,v);add_edge(y,x,v);}dfs(1,0,0);pos2 = pos1;dfs(pos1,0,0);cout<<maxx<<endl;return 0; }- 法2:dp
- 時間復雜度O(n)
- 優點:寫起來簡單
- 缺點:不好記錄路徑
總結
以上是生活随笔為你收集整理的poj1985 Cow Marathon(树的直径#入门)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小翔和泰拉瑞亚(线段树+思维)
- 下一篇: #1176 : 欧拉路·一(欧拉通路的判