题解:P6168 [IOI 2016] railroad
神仙题。
每个轨道恰好经过一次,容易误导到最短哈密顿路径,但这是 NPC 的所以就倒闭了。我们考虑隔壁欧拉路径,目标把点转化边。
首先你能观察到一个显然的性质:我们不会消耗代价去加速,因为每个轨道接受的速度是小于等于
考虑以速度为点,那么轨道
为了更好刻画初始状态,我们引入新轨道
回忆欧拉路径存在的充要条件:每个点的入度出度相等,图连通。
先考虑第一个条件。对于每条边
再考虑第二个条件。我们已经给
加个离散化就做完了,贴代码。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 400100, inf = 2e9;
int n, m, hs[N], s, cf[N], fa[N], ans, cnt;
struct road{int u, v;} a[N];
int getuid(int x) {return lower_bound(hs + 1, hs + 1 + s, x) - hs;}
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]);}
void merge(int x, int y) { fa[find(x)] = find(y);}
struct edge{ int u, v, w;} e[N];
bool cmp(edge x, edge y) { return x.w < y.w;}
signed main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> a[i].u >> a[i].v;
a[++n] = {inf, 1};
for(int i = 1; i <= n; i++) hs[++s] = a[i].u, hs[++s] = a[i].v;
sort(hs + 1, hs + 1 + s);
s = unique(hs + 1, hs + 1 + s) - hs - 1;
for(int i = 1; i <= s; i++) fa[i] = i;
for(int i = 1; i <= n; i++) {
a[i].u = getuid(a[i].u), a[i].v = getuid(a[i].v);
merge(a[i].u, a[i].v);
++cf[a[i].u], --cf[a[i].v];
}
for(int i = 1; i < s; i++) {
cf[i] += cf[i - 1];
if(cf[i] > 0) ans += (hs[i + 1] - hs[i]) * cf[i], merge(i, i + 1);
if(cf[i] < 0) merge(i, i + 1);
}
for(int i = 1; i < s; i++) if(find(i) != find(i + 1)) e[++cnt] = {i, i + 1, hs[i + 1] - hs[i]};
sort(e + 1, e + 1 + cnt, cmp);
for(int i = 1; i <= cnt; i++)
if(find(e[i].u) != find(e[i].v))
ans += e[i].w, merge(e[i].u, e[i].v);
cout << ans;
return 0;
}