POJ2631-Roads in the North(树的最长路径)

随便找一个点u,用DFS求出u的最远结点v,然后再利用一次DFS求出v的最远结点w,则v-w就是最长路径.

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm> 
#define maxn 10010
using namespace std;
typedef long long ll;

struct Node{
    Node(int a, int b, int c){
        x = a;
        y = b;
        s = c;
    }
    int x, y, s;
};
vector<Node> edge;
vector<int> v[maxn];
ll maxs;
int p;
void dfs(int n, int f, ll h){

    if(v[n].size() == 1 && edge[v[n][0]].y == f){
        if(h > maxs){
            maxs = h;
            p = n;
        }
        return ;
    }
    for(int i = 0; i < v[n].size(); i++){

        Node &e = edge[v[n][i]];
        if(e.y != f){
            dfs(e.y, e.x, h+e.s);
        }
    }
}
int main(){

// freopen("in.txt", "r", stdin);
    int a, b, c;

    while(scanf("%d%d%d", &a, &b, &c) == 3){

        edge.push_back(Node(a, b, c));
        edge.push_back(Node(b, a, c));
        v[a].push_back(edge.size()-2);
        v[b].push_back(edge.size()-1);
    }
    maxs = 0;
    dfs(1, -1, (ll)0);
    maxs = 0;
    dfs(p, -1, (ll)0);

    cout << maxs << endl;

    return 0;
}

你可能感兴趣的:(POJ2631-Roads in the North(树的最长路径))