跳到正文

题解

题解 CF1844F2 【Min Cost Permutation (Hard Version)】

Leasier约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年7月18日
收录
2026年5月23日
更新
2026年11月10日
篇幅
约 4 分钟
题目
CF1844F2

版本

  1. v1当前

请先查看这篇题解。

现在我们只考虑 c<0c < 0 的情况。

考虑硬拆调整法中的不等式。忽略 i=1i = 1 或 j=nj = n 的情况并给值相同的 ai,ai+1a_i, a_{i + 1} 钦定大小顺序可得:

  • aj+1−aj−1≥ca_{j + 1} - a_{j - 1} \geq c 且 aj−bi−1≥ca_j - b_{i - 1} \geq c。

注意到 b1=a1b_1 = a_1,考虑从这里开始一个一个调整出正确的 bib_i 以避免 i=1i = 1 的特判。

用一个 set 维护所有满足 aj+1−aj−1≥ca_{j + 1} - a_{j - 1} \geq c 的二元组 (aj,j)(a_j, j),每次取出 aja_j 最小的满足该条件者(如不存在则取出全局最大者,这里相当于是对 jj 相关的 corner case 的特批)加入答案,并用一个双向链表维护“ai−1,ai+1a_{i - 1}, a_{i + 1}”即可。

时间复杂度为 O(∑nlog⁡n)O(\sum n \log n)。

代码:

C++
#include <iostream>
#include <algorithm>
#include <set>

using namespace std;

typedef long long ll;

int a[200007], l[200007], r[200007], ans[200007];
set<pair<int, int> > s;

int main(){
	int t;
	cin >> t;
	for (int i = 1; i <= t; i++){
		int n, c;
		cin >> n >> c;
		for (int j = 1; j <= n; j++){
			cin >> a[j];
		}
		if (c >= 0){
			sort(a + 1, a + n + 1);
			for (int j = 1; j <= n; j++){
				ans[j] = a[j];
			}
		} else {
			sort(a + 1, a + n + 1, greater<int>());
			l[n + 1] = n;
			r[0] = 2;
			for (int j = 2; j <= n; j++){
				l[j] = j == 2 ? 0 : j - 1;
				r[j] = j + 1;
			}
			ans[1] = a[1];
			for (int j = 3; j < n; j++){
				if (a[r[j]] - a[l[j]] >= c) s.insert(make_pair(a[j], j));
			}
			for (int j = 2; j <= n; j++){
				int pos, p, q;
				set<pair<int, int> >::iterator it = s.lower_bound(make_pair(ans[j - 1] + c, 0));
				if (it == s.end()){
					pos = r[0];
				} else {
					pos = it->second;
					s.erase(it);
				}
				ans[j] = a[pos];
				p = l[pos];
				q = r[pos];
				r[p] = q;
				l[q] = p;
				if (l[p] == 0 || q > n || a[q] - a[l[p]] < c) s.erase(make_pair(a[p], p));
				if (p == 0 || r[q] > n || a[r[q]] - a[p] < c) s.erase(make_pair(a[q], q));
			}
		}
		for (int j = 1; j <= n; j++){
			cout << ans[j] << " ";
		}
		cout << endl;
	}
	return 0;
}
原文
存档评论1 条抓取于