fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. int main() {
  8. //cin.tie(0)->sync_with_stdio(0);
  9. int t; cin >> t;
  10. while (t--) {
  11. int n; cin >> n;
  12. vector<int> a(n);
  13. vector<pair<int, int>> alive; // {a[i], i}
  14. for (int &x : a) {
  15. cin >> x;
  16. if (x == -1) x = n + 1;
  17. }
  18.  
  19. for (int i = 0; i < n; i++) {
  20. alive.push_back(make_pair(a[i], i));
  21. }
  22.  
  23. vector<int> l(n), r(n);
  24. for (int i = 0; i < n; i++) {
  25. l[i] = i - 1;
  26. r[i] = i + 1;
  27. }
  28.  
  29. vector<vector<int>> adj(n);
  30. sort(alive.rbegin(), alive.rend());
  31.  
  32. vector<int> indegree(n, 0), ans(n);
  33.  
  34. int step = 1;
  35. while (alive.size() > 1) {
  36.  
  37. // (u, v) -> p[u] > p[v]
  38. for (auto p : alive) {
  39. if (p.first == step) continue;
  40. int u = p.second;
  41. if (l[u] >= 0) {
  42. if (step % 2 == 1) { // u is local min
  43. adj[l[u]].push_back(u);
  44. indegree[u]++;
  45. } else {
  46. adj[u].push_back(l[u]);
  47. indegree[l[u]]++;
  48. }
  49. }
  50. if (r[u] < n) {
  51. if (step % 2 == 1) {
  52. adj[r[u]].push_back(u);
  53. indegree[u]++;
  54. } else {
  55. adj[u].push_back(r[u]);
  56. indegree[r[u]]++;
  57. }
  58. }
  59. }
  60. while (alive.size() > 0 && alive.back().first == step) {
  61. int idx = alive.back().second;
  62. if (l[idx] >= 0) r[l[idx]] = r[idx];
  63. if (r[idx] < n) l[r[idx]] = l[idx];
  64. alive.pop_back();
  65. }
  66. step++;
  67. }
  68.  
  69. // for (int i = 0; i < n; i++) {
  70. // for (int j : adj[i]) {
  71. // cout << "(" << i << ", " << j << ")" << '\n';
  72. // }
  73. // }
  74.  
  75. queue<int> q;
  76. for (int i = 0; i < n; i++) if (indegree[i] == 0) q.push(i);
  77.  
  78. int val = n;
  79. while (!q.empty()) {
  80. int u = q.front(); q.pop();
  81. ans[u] = val--;
  82. for (int v : adj[u]) {
  83. indegree[v]--;
  84. if (indegree[v] == 0) q.push(v);
  85. }
  86. }
  87.  
  88. for (int x : ans) cout << x << ' ';
  89. cout << '\n';
  90. }
  91. }
  92.  
  93.  
Success #stdin #stdout 0s 5316KB
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
3 2 1 
5 2 4 1 3 
4 8 2 7 3 6 5 1 
7 6 5 1 4 3 2 
5 4 3 2 1 
1 5 4 3 2 
3 5 1 4 2