fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main(){
  5. ios::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7.  
  8. int t;
  9. cin >> t;
  10. while(t--){
  11. int n;
  12. cin >> n;
  13. vector<int> a(n), depth(n);
  14. int T = 0, final_pos = -1;
  15.  
  16. // read a[], build depth[], find T=max(a)
  17. for(int i = 0; i < n; i++){
  18. cin >> a[i];
  19. if(a[i] == -1){
  20. depth[i] = -1; // mark final survivor
  21. final_pos = i;
  22. } else {
  23. depth[i] = a[i];
  24. T = max(T, a[i]);
  25. }
  26. }
  27. // interpret depth=-1 as T+1
  28. for(int i = 0; i < n; i++){
  29. if(depth[i] < 0) depth[i] = T+1;
  30. }
  31.  
  32. vector<int> alive(n), p(n);
  33. iota(alive.begin(), alive.end(), 0);
  34.  
  35. int lval = 1, rval = n;
  36. // peel off rounds 1..T
  37. for(int d = 1; d <= T; d++){
  38. vector<int> next_alive;
  39. vector<vector<int>> blocks;
  40. vector<int> cur;
  41.  
  42. // split alive into runs where depth==d (to remove)
  43. // and survivors depth>d
  44. for(int idx: alive){
  45. if(depth[idx] == d){
  46. cur.push_back(idx);
  47. }
  48. else { // depth[idx] > d
  49. if(!cur.empty()){
  50. blocks.push_back(cur);
  51. cur.clear();
  52. }
  53. next_alive.push_back(idx);
  54. }
  55. }
  56. if(!cur.empty())
  57. blocks.push_back(cur);
  58.  
  59. // assign each block
  60. if(d & 1){
  61. // odd round: remove non‐minima → these must be LARGER than neighbours
  62. // take from rval downward, but within each block assign in descending order
  63. for(auto &blk: blocks){
  64. for(int j = (int)blk.size()-1; j >= 0; --j){
  65. p[ blk[j] ] = rval--;
  66. }
  67. }
  68. } else {
  69. // even round: remove non‐maxima → these must be SMALLER than neighbours
  70. // take from lval upward, assign in ascending order
  71. for(auto &blk: blocks){
  72. for(int j = 0; j < (int)blk.size(); ++j){
  73. p[ blk[j] ] = lval++;
  74. }
  75. }
  76. }
  77.  
  78. alive.swap(next_alive);
  79. }
  80.  
  81. // exactly one left
  82. p[ alive[0] ] = lval; // lval == rval here
  83.  
  84. // output
  85. for(int i = 0; i < n; i++){
  86. cout << p[i] << (i+1<n?' ':'\n');
  87. }
  88. }
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 5284KB
stdin
7
3
1 1 -1
5
1 -1 1 2 1
8
3 1 2 1 -1 1 1 2
7
1 1 1 -1 1 1 1
5
1 1 1 1 -1
5
-1 1 1 1 1
5
-1 1 2 1 2
stdout
2 3 1
5 2 4 1 3
4 8 1 7 3 5 6 2
5 6 7 1 2 3 4
2 3 4 5 1
1 2 3 4 5
3 5 1 4 2