POJ 1985 Cow Marathon 树的直径

求一棵树上的最长路,即树的直径。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <stack>
#include <map>
#include <iomanip>
#define PI acos(-1.0)
#define Max 20005
#define inf 1<<28
#define LL(x) (x<<1)
#define RR(x) (x<<1|1)
#define FOR(i,s,t) for(int i=(s);i<=(t);++i)
#define ll long long
#define mem(a,b) memset(a,b,sizeof(a))
#define mp(a,b) make_pair(a,b)
using namespace std;

int n , m ;
struct kdq
{
    int e , l , next ;
}ed[Max * 100] ;
int head[Max * 10 ], num ,ans = 0 ;
bool vis[Max * 10 ];
int dis[Max * 10 ];
void add(int s , int v ,int l )
{
    ed[num].e = v ;
    ed[num].l = l ;
    ed[num].next = head[s];
    head[s] = num ++;
}
void init()
{
    num = 0 ;
    ans = 0 ;
    mem(head,-1);
    mem(dis,0);
}

void bfs(int now )
{
    queue<int>qe;
    qe.push(now);
    vis[now] = 1 ;
    dis[now] = 0 ;
    int v = now ;
    int vv = dis[now] ;
    while(!qe.empty())
    {
        int tt = qe.front();
        qe.pop();
        for (int i = head[tt] ; i != -1 ;i = ed[i].next )
        {
            int t = ed[i].e ;
            int l = ed[i].l ;
            if(vis[t])continue;
            vis[t] = 1 ;
            dis[t] = dis[tt] + l ;
            if(vv < dis[t])v = t , vv = dis[t] ;
            qe.push(t);
        }
    }
    mem(vis,0);
    while(!qe.empty())qe.pop();
    qe.push(v);
    vis[v] = 1 ;
    dis[v] = 0 ;
    while(!qe.empty())
    {
        int tt = qe.front() ;
        qe.pop() ;
        for (int i = head[tt] ; i != -1 ;i = ed[i].next )
        {
            int t = ed[i].e ;
            int l = ed[i].l ;
            if(vis[t])continue;
            vis[t] = 1 ;
            dis[t] = dis[tt] + l ;
            if(dis[t] > ans)ans = dis[t] ;
            qe.push(t);
        }
    }
}
int main()
{
    while(cin >> n >> m)
    {
        init();
        for (int i = 0 ;i < m ;i ++)
        {
            int a , b ,c ;
            char d ;
            scanf("%d%d%d",&a,&b,&c);
            cin >> d;
            add(a,b,c);
            add(b,a,c);
        }
        bfs(1);
        cout <<ans<<endl;
    }
    return 0;
}


你可能感兴趣的:(POJ 1985 Cow Marathon 树的直径)