【poj Roads in the North】 题解

题目链接:http://poj.org/problem?id=2631

求树的直径模板。

定理:

树上任意一个点的在树上的最长路一定以树的直径的两端点其中一点结束。

做法:

两边bfs,第一次先找到node(树的直径的两端点其中一个),再一次求node的最长路所结束的点t
node—>t就是树的直径

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int n, dis[maxn], ans, node;
bool vis[maxn];
struct edge{
    int from, to, next, len;
}e[maxn<<2];
int cnt, head[maxn];
void add(int u, int v, int w)
{
    e[++cnt].from = u;
    e[cnt].next = head[u];
    e[cnt].len = w;
    e[cnt].to = v;
    head[u] = cnt;
}
queue<int> q;
void bfs(int s)
{
    vis[s] = 1;
    q.push(s);
    while(!q.empty())
    {
        int now = q.front(); q.pop();
        for(int i = head[now]; i != -1; i = e[i].next)
        {
            if(vis[e[i].to] == 0)
            {
                dis[e[i].to] = dis[now] + e[i].len;
                vis[e[i].to] = 1;
                q.push(e[i].to);
                if(dis[e[i].to] > ans)
                {
                    ans = dis[e[i].to];
                    node = e[i].to;
                }
            }
        }
    }
}
int main()
{
    memset(head, -1, sizeof(head));
    int u, v, w;
    while(scanf("%d%d%d",&u, &v, &w) == 3)
    {
        add(u, v, w);
        add(v, u, w);
    }
    memset(dis, 0, sizeof(dis));
    memset(vis, 0, sizeof(vis));
    ans = 0;
    bfs(1);
    
    memset(vis, 0, sizeof(vis));
    dis[node] = 0;
    ans = 0;
    bfs(node);
    
    printf("%d\n", ans);
    return 0;
}

//Misaka_Azusa
//dsbdsb

posted @ 2018-10-12 16:32  Misaka_Azusa  阅读(112)  评论(0编辑  收藏  举报
Live2D