码迷,mamicode.com
首页 > 其他好文 > 详细

[Poj] Roads in the North

时间:2018-01-14 13:07:54      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:lan   body   title   get   size   def   int   can   poi   

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

标签:lan   body   title   get   size   def   int   can   poi   

原文地址:https://www.cnblogs.com/shandongs1/p/8282592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!