POJ1985 树的直径(BFS
Posted mj-liylho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ1985 树的直径(BFS相关的知识,希望对你有一定的参考价值。
Cow Marathon
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 6526 | Accepted: 3144 | |
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
题意:求树上最长路。
容易发现:求一个连通块中的最长路径,首先,从该连通块中任意一个结点出发,求最长路径的端点是S,然后再从S出发求最长路径L,路径L就是要求的路径。
代码:
1 #include"bits/stdc++.h" 2 3 #define db double 4 #define ll long long 5 #define vl vector<ll> 6 #define ci(x) scanf("%d",&x) 7 #define cd(x) scanf("%lf",&x) 8 #define cl(x) scanf("%lld",&x) 9 #define pi(x) printf("%d ",x) 10 #define pd(x) printf("%f ",x) 11 #define pl(x) printf("%lld ",x) 12 #define rep(i, a, n) for (int i=a;i<n;i++) 13 #define per(i, a, n) for (int i=n-1;i>=a;i--) 14 #define fi first 15 #define se second 16 using namespace std; 17 typedef pair<int, int> pii; 18 const int N = 1e6 + 5; 19 const int mod = 1e9 + 7; 20 const int MOD = 998244353; 21 const db PI = acos(-1.0); 22 const db eps = 1e-10; 23 const int inf = 0x3f3f3f3f; 24 const ll INF = 0x3fffffffffffffff; 25 int t, n, m; 26 bool vis[N]; 27 char ss[200]; 28 vector<pii> e[N]; 29 queue<int> q; 30 void add(int u,int v,int w){ 31 e[u].push_back(pii(v,w)); 32 } 33 int ma; 34 int f[N]; 35 int s; 36 void BFS(int x)//BFS求最长路 37 { 38 memset(f,0, sizeof(f)); 39 memset(vis,0, sizeof(vis)); 40 while(!q.empty()) q.pop(); 41 ma=0; 42 q.push(x); 43 vis[x]=1; 44 s=x; 45 while(!q.empty()){ 46 int u=q.front();q.pop(); 47 for(int i=0;i<e[u].size();i++){ 48 int v=e[u][i].fi; 49 int w=e[u][i].se; 50 if(!vis[v]){ 51 if(f[v]<f[u]+w) f[v]=f[u]+w; 52 vis[v]=1; 53 q.push(v); 54 } 55 if(ma<f[v]) ma=f[v],s=v; 56 } 57 } 58 } 59 int main() { 60 61 while (scanf("%d%d", &n, &m) == 2) { 62 for(int i=0;i<=n;i++) e[i].clear(); 63 for (int i = 0; i < m; i++) { 64 int x, y, z; 65 scanf("%d %d %d %s", &x, &y, &z, ss); 66 add(x,y,z),add(y,x,z); 67 } 68 BFS(1); 69 BFS(s); 70 pi(ma); 71 } 72 return 0; 73 }
以上是关于POJ1985 树的直径(BFS的主要内容,如果未能解决你的问题,请参考以下文章