UVa 10308 Roads in the North(DFS)

题意:

给定一张图,其实是一个二叉树,求二叉树中节点的最大距离。

思路:

其实这一题就是编程之美上面的:求二叉树中节点的最大距离。

这个最大距离肯定是两个叶子节点之间的,于是dfs遍历二叉树就行了。

#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;

struct Node {
    int e, len;
    Node(int _end, int _len) : e(_end), len(_len) { }
};

const int MAXN = 10010;
vector<Node> g[MAXN];

int ans;

int dfs(int u, int r)
{
    int tmax = 0, tans;
    for (int i = 0; i < g[u].size(); ++i)
    {
        int v = g[u][i].e;
        if (v != r)
        {
            tans = dfs(v, u) + g[u][i].len;
            if (tans + tmax > ans)
                ans = tans + tmax;
            if (tans > tmax)
                tmax = tans;
        }
    }
    return tmax;
}

int main()
{
    string s;
    while (!cin.eof())
    {
        for (int i = 0; i < MAXN; ++i)
            g[i].clear();

        getline(cin, s);
        while (s.length() > 0 && !cin.eof())
        {
            stringstream ss;
            ss << s;
            int u, v, len;
            ss >> u >> v >> len;
            g[u].push_back(Node(v, len));
            g[v].push_back(Node(u, len));

            getline(cin, s);
        }

        ans = 0;
        dfs(1, -1);
        cout << ans << endl;
    }
    return 0;
}
-------------------------------------------------------

kedebug

Department of Computer Science and Engineering,

Shanghai Jiao Tong University

E-mail: kedebug0@gmail.com

GitHub: http://github.com/kedebug

-------------------------------------------------------

原文地址:https://www.cnblogs.com/kedebug/p/2810430.html