跳到正文

题解

CF1784C题解

xcyle约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF1784C

版本

  1. v1当前

提供一种码量较小的做法。

容易发现,对于单个问题,我们可以这样求解:

维护变量 levlev,初始为 11。每次找到剩下的数中,不小于 levlev 的数中最小的一个,记为 xx。将答案加上 x−levx-lev,并把 xx 删掉。直到不存在不小于 levlev 的数停止。

我们把上述过程中所有找到的 xx 放进一个可重集 ss 中,其它数放进另一个可重集 tt 中。

考虑倒序,将加数变为删数。假设删除的数是 aa。只有 a∈Sa\in S 时,答案才有可能改变。接下来我们考虑对上述过程的修正。

若 tt 中存在不小于 aa 的数,记其中最小的一个是 yy。我们需要将 yy 从 tt 中删除,加入 ss 。这是因为,假设 ss 中不小于 yy 的最大数为 zz。那么删除 zz 的操作进行的时候,原本的 levlev 满足 lev≤zlev\le z,而将 aa 删掉后,这个时刻的 levlev 会 −1-1,因此在删除 zz 的下一轮,我们寻找不小于 levlev 的最小数时,就会找到 yy。而 yy 又是第一个没被删除的,因此结论得证。

若 tt 中不存在不小于 aa 的数,那么修正就是将过程的最后一轮删掉。

两种情况对答案的影响都能简单计算,复杂度 O(nlog⁡n)O(n\log n),代码比较好写。

C
#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();}
原文