题解:P6270 [湖北省队互测 2014] 十万人的地铁
模拟赛搬运了这个题。
首先胡搞一通之后发现最小的代价好像是
考虑这个式子的意义:即
假设
现在我们发现刚才干的事情其实是将一个置换环中的一条边打掉,故考虑拎出每个置换环单独考虑(在代码实现中从
令
对于一个置换环的两个人,我们有六种情况(偷一张题解的图):
对于第 3 种,第 4 种和第 5 种,我们发现
对于第 1 种,第 2 种和第 6 种,我们直接做的话次数会爆炸,但是我们此时
显然最终次数为
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#define int long long
using namespace std;
int n, m;
struct ST {
int num, id;
bool operator<(const ST &y) const {
if(num != y.num) return num > y.num;
return id > y.id;
}
}s[100010], t[100010];
int ts[100010], tt[100010];
bool cmp(ST x, ST y) {
if(x.num != y.num) return x.num < y.num;
return x.id < y.id;
}
struct OP {
int op, x, y;
};
vector<OP> z, f;
set<ST> pqs, pqt;
signed main() {
int T;
cin >> T;
while(T--) {
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> s[i].num >> t[i].num, s[i].id = t[i].id = i, ts[i] = s[i].num, tt[i] = t[i].num;
sort(s + 1, s + n + 1, cmp);
sort(t + 1, t + n + 1, cmp);
int sm = 0;
for(int i = 1; i <= n; i++) sm += ((s[i].num - t[i].num < 0) * -2 + 1) * (s[i].num - t[i].num), pqs.insert(s[i]), pqt.insert(t[i]);
cout << sm << ' ';
z.clear(), f.clear();
int cnt = 0;
while(!pqs.empty()) {
int x = pqs.begin()->id, y = pqt.begin()->id;
//cerr << x << ' ' << y << ' ' << ts[x] << ' ' << tt[x] << ' ' << ts[y] << ' ' << tt[y] << '\n';
pqs.erase((ST){ts[x], x}), pqs.erase((ST){ts[y], y});
pqt.erase((ST){tt[x], x}), pqt.erase((ST){tt[y], y});
//cerr << x << ' ' << y << ' ' << ts[x] << ' ' << tt[x] << ' ' << ts[y] << ' ' << tt[y] << ' ' << (tt[x] <= ts[y]) << '\n';
if(x == y) {
if(ts[x] != tt[x]) z.push_back({0, x, tt[x]}), cnt++;
}
else if(tt[x] <= ts[y]) {
if(ts[x] != ts[y]) z.push_back({0, x, ts[y]}), cnt++;
z.push_back({1, x, y}), cnt++;
if(ts[y] != tt[y]) z.push_back({0, y, tt[y]}), cnt++;
ts[x] = ts[y];
pqs.insert({ts[x], x}), pqt.insert({tt[x], x}); // x 在 s_y 要到 t_x
}
else { // tt[x] <= tt[y]
if(tt[x] != tt[y]) f.push_back({0, y, tt[y]}), cnt++;
f.push_back({1, x, y}), cnt++;
if(ts[x] != tt[x]) f.push_back({0, x, tt[x]}), cnt++; // 最后倒序执行
tt[y] = tt[x]; // 要先把 y 弄到 t_x,然后 x 到 t_x 后交换,然后 y 再把 x 的东西送到 t_y 因为倒序执行所以先到 t_x
pqs.insert({ts[y], y}), pqt.insert({tt[y], y}); // y 从 s_y 到 t_x
}
}
cout << cnt << '\n';
for(int i = 0; i < z.size(); i++) cout << z[i].op << ' ' << z[i].x << ' ' << z[i].y << '\n';
for(int i = f.size() - 1; i >= 0; i--) cout << f[i].op << ' ' << f[i].x << ' ' << f[i].y << '\n';
}
return 0;
}