fork download
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. #define pb push_back
  7. #define forn(i,n) for (int i=0;i<(int)n;i++)
  8.  
  9. using namespace std;
  10. int n; int root = 0;
  11. vector <int> g[100500];
  12. int p[100500];
  13.  
  14. void go()
  15. {
  16. int par = root;
  17.  
  18. while (par != root || !g[par].empty())
  19. {
  20. if (g[par].empty())
  21. {
  22. cout << par << " ";
  23. par = p[par];
  24. g[par].pop_back();
  25. continue;
  26. }
  27. par = *g[par].rbegin();
  28. }
  29. cout << root << endl;
  30. }
  31.  
  32. bool cmp(int a,int b) { return a > b; }
  33.  
  34. int main() {
  35. cin >> n;
  36. forn(i,n-1)
  37. {
  38. int par; scanf("%d",&par);
  39. p[i+1] = par;
  40. g[par].pb(i+1);
  41. }
  42. forn(i,n) sort(g[i].begin(),g[i].end(),cmp);
  43.  
  44. go();
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0.02s 4432KB
stdin
10
8
0
2
2
4
4
4
0
8
stdout
3 5 6 7 4 2 1 9 8 0