请先查看这篇题解。
现在我们只考虑 的情况。
考虑硬拆调整法中的不等式。忽略 或 的情况并给值相同的 钦定大小顺序可得:
- 且 。
注意到 ,考虑从这里开始一个一个调整出正确的 以避免 的特判。
用一个 set 维护所有满足 的二元组 ,每次取出 最小的满足该条件者(如不存在则取出全局最大者,这里相当于是对 相关的 corner case 的特批)加入答案,并用一个双向链表维护“”即可。
时间复杂度为 。
代码:
#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;
}