[Poj] Roads in the North

Posted xayata

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Poj] Roads in the North相关的知识,希望对你有一定的参考价值。

http://poj.org/problem?id=2631

树的直径裸题

dfs/bfs均可

/*
    dfs
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>

using namespace std;
const int N = 1e5 + 10; 

#define yxy getchar()

int now = 1, point, Max_dis;
int dis[N], head[N];
bool vis[N];
struct Node {int v, w, nxt;} G[N << 1];

inline void add(int u, int v, int w){
    G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++;
}

void dfs(int u, int dist){
    for(int i = head[u]; ~ i; i = G[i].nxt){
        int v = G[i].v;
        if(!vis[v]){
            dis[v] = dist + G[i].w;
            vis[v] = 1;
            if(dis[v] > Max_dis){
                Max_dis = dis[v];
                point = v; 
            }
            dfs(v, dis[v]);
        }
    }
}

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_);
    }
    vis[1] = 1;
    dfs(1, 0);
    Max_dis = 0;
    memset(vis, 0, sizeof(vis));
    vis[point] = 1;
    dfs(point, 0);
    cout << Max_dis;
    return 0;
}
/*
    bfs
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>

using namespace std;
const int N = 1e5 + 10; 

#define yxy getchar()

int now = 1, point, Max_dis;
int dis[N], head[N];
bool vis[N];
struct Node {int v, w, nxt;} G[N << 1];
queue <int> Q;

inline void add(int u, int v, int w){
    G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++;
}

void bfs(int S){
    Q.push(S);
    vis[S] = 1;
    while(!Q.empty()){
        int topp = Q.front();
        Q.pop();
        for(int i = head[topp]; ~ i; i = G[i].nxt){
            int v = G[i].v;
            if(!vis[v]){
                vis[v] = 1;
                dis[v] = dis[topp] + G[i].w;
                Q.push(v);
                if(dis[v] > Max_dis){
                    Max_dis = dis[v];
                    point = v; 
                }
            }
        } 
    }
}

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_);
    }
    bfs(1);
    Max_dis = 0;
    memset(vis, 0, sizeof(vis));
    memset(dis, 0, sizeof(dis));
    bfs(point);
    cout << Max_dis;
    return 0;
}

 

以上是关于[Poj] Roads in the North的主要内容,如果未能解决你的问题,请参考以下文章

题解报告:poj 2631 Roads in the North(最长链)

poj2631 ?Roads in the North(求树的直径)

POJ2631 Roads in the North

poj Roads in the North 题解

Roads in the North (树的直径)

UVA10308 Roads in the North 树的最长路径