• 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

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

  • 相关阅读:
    Java使用POI操作Excel合并单元格
    LinkedList查询分析
    Redis面试题及答案
    分布式架构基础:Java RMI详解
    什么是线程
    ehcache、memcache、redis三大缓存比较
    ehcache入门基础示例
    js 异步提交文件
    .net core Model对象转换为uri网址参数形式
    net core2.1 在过滤器中获取post的body参数
  • 原文地址:https://www.cnblogs.com/kedebug/p/2810430.html
Copyright © 2020-2023  润新知