Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n;
  6. vector <vector <int> > graph;
  7. vector <deque <int> > result;
  8. vector <int> position_of_answer;
  9. vector <pair <int, int> > all;
  10.  
  11. void dfs(int v) {
  12. for (auto to : graph[v])
  13. dfs(to);
  14. /**int pos = v;
  15. for (auto to : graph[v]) {
  16. if ((int)result[position_of_answer[to]].size() > (int)result[position_of_answer[pos]].size())
  17. pos = position_of_answer[to];
  18. }
  19. position_of_answer[v] = pos;**/
  20. result[v].push_back(v);
  21. for (auto to : graph[v]) {
  22. //if (to == graph[v].back())
  23. //reverse(result[to].begin(), result[to].end());
  24. all.push_back({result[to][0], result[to].back()});
  25. for (auto el : result[to])
  26. result[v].push_back(el);
  27. result[to].clear();
  28. }
  29. }
  30.  
  31. int main() {
  32. ios_base::sync_with_stdio(false);
  33. cin.tie(nullptr);
  34. cout.tie(nullptr);
  35. cin >> n;
  36. graph.resize(n);
  37. result.resize(n);
  38. position_of_answer.resize(n);
  39. for (int i = 0; i < n - 1; i++) {
  40. int x;
  41. cin >> x;
  42. graph[x - 1].push_back(i + 1);
  43. }
  44. dfs(0);
  45. map <int, int> smth;
  46. for (int i = 0; i < n; i++)
  47. smth[result[0][i]] = i;
  48. vector <int> used(n, -1);
  49. for (auto el : all) {
  50. int l = el.first, r = el.second;
  51. //cout << l << " " << r << "aaa\n";
  52. if (used[r] == -1 || used[r] > smth[l])
  53. used[r] = smth[l];
  54. }
  55. vector <int> ans(n);
  56. for (int i = 0; i < n; i++) {
  57. if (used[i] == -1)
  58. continue;
  59. int l = used[i], r = smth[i];
  60. int step = 0;
  61. //cout << l << " " << r << endl;
  62. for (int j = l + 1; j <= r; j += 2) {
  63. ans[l + step] = result[0][j];
  64. step++;
  65. }
  66. for (int j = r - (r - l) % 2; j >= l; j -= 2) {
  67. ans[l + step] = result[0][j];
  68. step++;
  69. }
  70. }
  71. for (auto el : ans)
  72. cout << el + 1 << " ";
  73. cout << "\n";
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement