1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (auto i = (a); i < decltype(a)(b); ++i)
#define ROF(i, a, b) for (auto i = decltype(b)(a) - 1; i >= (b); --i)
using i64 = long long;
namespace IN {
char buf[1 << 21], *p1 = buf, *p2 = buf;
inline char getchar() { return p1 == p2 && (p2 = (p1 = buf) + cin.rdbuf()->sgetn(buf, 1 << 21), p1 == p2) ? EOF : *p1++; }
inline void read(auto& p) {
p = 0; char ch = getchar();
for (; !isdigit(ch); ch = getchar());
for (; isdigit(ch); ch = getchar()) p = p * 10 + (ch ^ 48);
}
void read(auto& p, auto&... args) { read(p); read(args...); }
}
using IN::read;
namespace Farewe1ll {
inline void solve() {
int n; read(n);
vector<int> a(n);
FOR (i, 0, n) read(a[i]);
// 构建笛卡尔树
vector ls(n, n), rs(n, n);
vector<int> stk; stk.reserve(n);
FOR (i, 0, n) {
int lst = n;
while (!stk.empty() && a[i] > a[stk.back()]) {
lst = stk.back();
stk.pop_back();
}
if (!stk.empty()) rs[stk.back()] = i;
ls[i] = lst;
stk.push_back(i);
}
int rt = max_element(a.begin(), a.end()) - a.begin();
// 第一次 dfs 预处理子树和
vector sum(n, 0ll);
auto dfs1 = [&](auto&& self, int u) -> i64 {
sum[u] = a[u];
for (auto v : {ls[u], rs[u]})
if (v < n) sum[u] += self(self, v);
return sum[u];
};
dfs1(dfs1, rt);
// 找寻目标节点
vector lm(n, n), rm(n, n), dst(n, n);
stk.clear();
FOR (i, 0, n) {
while (!stk.empty() && a[stk.back()] <= a[i]) stk.pop_back();
if (!stk.empty()) lm[i] = stk.back();
stk.push_back(i);
}
stk.clear();
ROF (i, n, 0) {
while (!stk.empty() && a[stk.back()] <= a[i]) stk.pop_back();
if (!stk.empty()) rm[i] = stk.back();
stk.push_back(i);
}
FOR (i, 0, n) {
if (lm[i] != n && rm[i] != n) dst[i] = a[lm[i]] > a[rm[i]] ? lm[i] : rm[i];
if (lm[i] == n && rm[i] != n) dst[i] = rm[i];
if (lm[i] != n && rm[i] == n) dst[i] = lm[i];
}
// 第二次 dfs 转移答案
vector ans(n, 0ll);
auto dfs2 = [&](auto&& self, int u) -> void {
for (auto v : {ls[u], rs[u]})
if (v < n) {
ans[v] = ans[u];
if (sum[v] < a[u]) ans[v] = ans[dst[v]] + 1;
self(self, v);
}
};
dfs2(dfs2, rt);
for (auto it : ans) cout << it << ' ';
cout << char(10);
}
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
int T = 1; read(T);
while (T--) Farewe1ll::solve();
return 0;
}
|