fork(12) download
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <vector>
  5. #include <iostream>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. #define MAXN 1024
  10.  
  11.  
  12. int l[MAXN + 1], r[MAXN + 1], d[MAXN + 1], n, t, k;
  13.  
  14. // calculates the depth of the current node and every child beneath it.
  15. void calc_depth(int cur, int depth)
  16. {
  17. d[cur] = depth;
  18. if (l[cur] > 0) calc_depth(l[cur], depth + 1);
  19. if (r[cur] > 0) calc_depth(r[cur], depth + 1);
  20. }
  21.  
  22. // prints the tree
  23. void in_order(int cur)
  24. {
  25. if (l[cur] > 0) in_order(l[cur]);
  26. cout << cur << " ";
  27. if (r[cur] > 0) in_order(r[cur]);
  28. }
  29.  
  30. // Input is sample #02
  31. int main()
  32. {
  33. // read input
  34. cin >> n;
  35. for (int i = 1; i <= n; i++) {
  36. cin >> l[i] >> r[i];
  37. }
  38.  
  39. // precalculation
  40. calc_depth(1, 1);
  41.  
  42. cin >> t;
  43. while (t--) {
  44. cin >> k;
  45.  
  46. for (int i = 1; i <= n; i++) {
  47. if (d[i] % k == 0) {
  48. // d[i] is a multiple of k
  49. // left child of i becomes right, and vice versa
  50. swap(l[i], r[i]);
  51. }
  52. }
  53.  
  54. // print the answer
  55. in_order(1);
  56. cout << endl;
  57. }
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 3156KB
stdin
11
2 3
4 -1
5 -1
6 -1
7 8
-1 9
-1 -1
10 11
-1 -1
-1 -1
-1 -1
2
2
4
stdout
2 9 6 4 1 3 7 5 11 8 10 
2 6 9 4 1 3 7 5 10 8 11