POJ1985 樹的直徑(BFS
阿新 • • 發佈:2018-08-28
comm fin john via org arc sed rep ati Cow Marathon
* Lines 1.....: Same input format as "Navigation Nightmare".
USACO 2004 February
題意:求樹上最長路。
容易發現:求一個連通塊中的最長路徑,首先,從該連通塊中任意一個結點出發,求最長路徑的端點是S,然後再從S出發求最長路徑L,路徑L就是要求的路徑。
代碼:
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
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
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\n",x) 10 #define pd(x) printf("%f\n",x) 11 #define pl(x) printf("%lld\n",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