zoukankan      html  css  js  c++  java
  • hihoCoder#1050 树中的最长路

    原题地址

    根据提示做即可,总感觉数据结构用的不好,以后看看大神都是怎么用数组存树的。

     1 #include <iostream>
     2 #include <vector>
     3 
     4 using namespace std;
     5 
     6 struct Node {
     7   int first;
     8   int second;
     9   bool rootp;
    10   vector<int> children;
    11   Node() : first(0), second(0), rootp(true) {}
    12 };
    13 
    14 int bestpath = 0;
    15 
    16 void traverse(Node *nodes, int root) {
    17   if (nodes[root].children.empty()) {
    18     nodes[root].first = 0;
    19     nodes[root].second = 0;
    20     return;
    21   }
    22 
    23   int first = 0;
    24   int second = 0;
    25 
    26   for (auto c : nodes[root].children) {
    27     traverse(nodes, c);
    28     second = max(second, min(first, nodes[c].first));
    29     first = max(first, nodes[c].first);
    30   }
    31   if (nodes[root].children.size() == 1)
    32     second = -1;
    33 
    34   nodes[root].first = first + 1;
    35   nodes[root].second = second + 1;
    36   bestpath = max(bestpath, nodes[root].first + nodes[root].second);
    37 }
    38 
    39 int main() {
    40   int N;
    41   int a, b;
    42   Node nodes[100010];
    43 
    44   cin >> N;
    45   for (int i = 1; i < N; i++) {
    46     cin >> a >> b;
    47     nodes[a - 1].children.push_back(b - 1);
    48     nodes[b - 1].rootp = false;
    49   }
    50 
    51   for (int i = 0; i < N; i++) {
    52     if (nodes[i].rootp) {
    53       traverse(nodes, i);
    54       break;
    55     }
    56   }
    57 
    58   cout << bestpath << endl;
    59 
    60   return 0;
    61 }
  • 相关阅读:
    rh
    re模块
    粘包现象
    子类调用父类方法
    北大医院条码
    戴德金-连续性和无理数-第1页
    数学名词
    核心英语笔记,含记忆术mnemonics
    python笔记
    收集的句子
  • 原文地址:https://www.cnblogs.com/boring09/p/4369268.html
Copyright © 2011-2022 走看看