poj 2631 Roads in the North (树的直径)
poj2631 题意:一棵树中求两个点的最远距离。。。 思路:就是求树的直径。。。裸体。。。。1A
/* ***********************************************
Author :111qqz
Created Time :2016年07月12日 星期二 13时03分39秒
File Name :code/poj/2631.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E4+7;
7int n,m;
8vector < pi> edge[N];
9int lst;
10int ans;
11int d[N];
12bool vis[N];
1void bfs( int s)
2{
3 ms(d,0x3f);
4 ms(vis,false);
5 queue<int>q;
6 q.push(s);
7 vis[s] = true;
8 d[s] = 0 ;
1 while (!q.empty())
2 {
3 int u = q.front() ; q.pop();
4 lst = u ;
5// cout<<"u:"<<u<<endl;
6 int siz = edge[u].size();
1 for ( int i = 0 ; i < siz ; i++)
2 {
3 int v = edge[u][i].fst;
4 if (vis[v]) continue;
5 vis[v] = true;
6 d[v] = d[u] + edge[u][i].sec;
7 ans = max(d[v],ans);
8 q.push(v);
9 }
10 }
1 int mx = 0;
2 for ( int i = 1 ; i <= n ; i++)
3 {
4// cout<<"i:"<<i<<" d[i]:"<<d[i]<<endl;
5 if (d[i]>mx)
6 {
7 mx = d[i];
8 lst = i ;
9 }
10 }
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
1 int u,v,w;
2 m = 0;
3 n = 0;
4 while (scanf("%d%d%d",&u,&v,&w)!=EOF)
5 {
6 edge[u].push_back(make_pair(v,w));
7 edge[v].push_back(make_pair(u,w));
8 m++;
9 n = max(n,u);
10 n = max(n,v);
11 }
12 ans = inf;
13 bfs(1);
14 ans = 0;
15// cout<<"lst:"<<lst<<endl;
16 bfs(lst);
17 cout<<ans<<endl;
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}