Advertisement
dmkozyrev

1517-accepted.cpp

Feb 10th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <functional>
  5. #include <cassert>
  6.  
  7. const bool DEBUG = false;
  8.  
  9. std::vector<std::vector<int>> edges;
  10.  
  11. void prepare(int curr, std::vector<int>& stack) {
  12.     stack.push_back(curr);
  13.     for (auto & next : edges[curr]) {
  14.         prepare(next, stack);
  15.     }
  16. }
  17.  
  18. int main() {
  19.     freopen("input.txt", "rt", stdin);
  20.     // freopen("output.txt", "wt", stdout);
  21.      
  22.     int nVert, degree;
  23.     scanf("%d %d", &nVert, &degree);
  24.      
  25.      
  26.     edges.assign(1+nVert, std::vector<int>());
  27.      
  28.     for (int b = 2; b <= nVert; ++b) {
  29.         int a;
  30.         scanf("%d", &a);
  31.         edges[a].push_back(b);
  32.     }
  33.      
  34.     if (DEBUG) {
  35.         printf("Edges:\n");
  36.         for (int v = 1; v <= nVert; ++v) {
  37.             printf("\t%d:", v);
  38.             for (auto & next : edges[v]) {
  39.                 printf(" %d", next);
  40.             }
  41.             printf("\n");
  42.         }
  43.         printf("\n");
  44.     }
  45.      
  46.     std::vector<std::pair<int, int>> height(1+nVert, {-1, -1});
  47.      
  48.     std::vector<int> stack;
  49.      
  50.     prepare(1, stack);
  51.      
  52.     while (!stack.empty()) {
  53.         int curr = stack.back(); stack.pop_back();
  54.         std::vector<int> temp{0, 0};
  55.         for (auto & next : edges[curr]) {
  56.             assert(height[next].first != -1);
  57.             temp.push_back(1+height[next].first);
  58.         }
  59.         std::sort(temp.begin(), temp.end(), std::greater<int>());
  60.         height[curr] = {temp[0], temp[1]};
  61.     }
  62.      
  63.     if (DEBUG) {
  64.         for (int v = 1; v <= nVert; ++v) {
  65.             printf("%d: %d %d\n", v, height[v].first, height[v].second);
  66.         }  
  67.     }
  68.      
  69.     int64_t max = (height[1].first+1LL) * degree;
  70.      
  71.     for (int v = 1; v <= nVert; ++v) {
  72.         if (height[v].first && height[v].second) {
  73.             max = std::max(1LL * max, (degree-1LL) * 2 * (height[1].first+1)+ height[v].first + height[v].second + 1);
  74.         }
  75.     }
  76.      
  77.     printf("%I64d", max);
  78.      
  79.      
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement