fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. int SV_sau[1000006];
  6. int SV_truoc[1000006];
  7. void init ()
  8. {
  9. for (int i=0; i<=1000000; i++)
  10. {
  11. SV_sau[i]=-1;
  12. SV_truoc[i]=-1;
  13. }
  14. }
  15.  
  16. vector <int> so;
  17. int dd[1000006] = {0};
  18. void check (int x)
  19. {
  20. if (dd[x]==0 && x!=0)
  21. {
  22. so.push_back(x);
  23. dd[x]=1;
  24. }
  25. }
  26.  
  27. int main ()
  28. {
  29. init ();
  30. int n;
  31. cin>>n;
  32. int vt1, vt2;
  33. for (int i=1; i<=n; i++)
  34. {
  35. int a, b;
  36. cin>>a>>b;
  37. check (a); check (b);
  38. SV_sau[a] = b;
  39. SV_truoc[b] = a;
  40. }
  41. vector <int> D1;
  42. vector <int> D2;
  43. if (n%2==0)
  44. {
  45. //Day 1
  46. int st = 0;
  47. while (1)
  48. {
  49. if (SV_sau[st]==-1) break;
  50. D1.push_back(SV_sau[st]);
  51. st = SV_sau[st];
  52. }
  53. // Day 2
  54. st = 0;
  55. while (1)
  56. {
  57. if (SV_truoc[st]==-1) break;
  58. D2.push_back(SV_truoc[st]);
  59. st = SV_truoc[st];
  60. }
  61. //IN
  62. int D_1 = 0, D_2 = D2.size()-1;
  63. for (int i=1; i<=n; i++)
  64. {
  65. if (i%2!=0)
  66. {
  67. cout<<D2[D_2]<<" ";
  68. D_2--;
  69. }
  70. else
  71. {
  72. cout<<D1[D_1]<<" ";
  73. D_1++;
  74. }
  75. }
  76. }
  77. else
  78. {
  79. //Day 1
  80. int st = 0;
  81. while (1)
  82. {
  83. if (SV_sau[st]==0) break;
  84. D1.push_back(SV_sau[st]);
  85. st = SV_sau[st];
  86. }
  87. st=0;
  88. for (int i=0; i<so.size(); i++)
  89. {
  90. if (SV_sau[so[i]]==-1)
  91. {
  92. st=so[i];
  93. break;
  94. }
  95. }
  96. if (st!=0) D2.push_back(st);
  97. while (1)
  98. {
  99. if (SV_truoc[st]==-1) break;
  100. D2.push_back(SV_truoc[st]);
  101. st = SV_truoc[st];
  102. }
  103. int D_1 = 0, D_2 = D2.size()-1;
  104. for (int i=1; i<=n; i++)
  105. {
  106. if (i%2!=0)
  107. {
  108. cout<<D2[D_2]<<" ";
  109. D_2--;
  110. }
  111. else
  112. {
  113. cout<<D1[D_1]<<" ";
  114. D_1++;
  115. }
  116. }
  117. }
  118. return 0;
  119. }
Success #stdin #stdout 0s 26960KB
stdin
4

92 31

0 7

31 0

7 141
stdout
92 7 31 141