提供一种码量较小的做法。
容易发现,对于单个问题,我们可以这样求解:
维护变量 ,初始为 。每次找到剩下的数中,不小于 的数中最小的一个,记为 。将答案加上 ,并把 删掉。直到不存在不小于 的数停止。
我们把上述过程中所有找到的 放进一个可重集 中,其它数放进另一个可重集 中。
考虑倒序,将加数变为删数。假设删除的数是 。只有 时,答案才有可能改变。接下来我们考虑对上述过程的修正。
若 中存在不小于 的数,记其中最小的一个是 。我们需要将 从 中删除,加入 。这是因为,假设 中不小于 的最大数为 。那么删除 的操作进行的时候,原本的 满足 ,而将 删掉后,这个时刻的 会 ,因此在删除 的下一轮,我们寻找不小于 的最小数时,就会找到 。而 又是第一个没被删除的,因此结论得证。
若 中不存在不小于 的数,那么修正就是将过程的最后一轮删掉。
两种情况对答案的影响都能简单计算,复杂度 ,代码比较好写。
#include <bits/stdc++.h>
#define N 200005
using namespace std;
int T, n, a[N], lev; long long res[N], ans;
multiset<int> t;
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i], t.insert(a[i]);
for (auto it = t.begin(); it != t.end(); it = t.upper_bound(lev)) {
ans += (*it) - ++lev;
t.erase(it);
}
for (int i = n; i >= 1; i--) {
res[i] = ans, ans -= a[i];
auto it = t.lower_bound(a[i]);
if(it == t.end()) ans += lev--;
else ans += (*it), t.erase(it);
}
for (int i = 1; i <= n; i++) printf("%lld ", res[i]); printf("\n");
}
int main() {cin >> T; while(T--) solve();}