zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    解决方案
    项目管理
    项目管理
    产品经理
    产品经理
    产品经理
    产品经理
    vue学习面向对象,在项目中怎么用呢?
    vue表单验证不通过,依然能执行点击事件里面的代码?
    vue中js文件中export常见方法及使用
  • 原文地址:https://www.cnblogs.com/kedebug/p/2810430.html
Copyright © 2011-2022 走看看