题解:P3837 [IOI 2017] Wiring
前言
被模拟费用流骗进来的,结果全是 dp,写一篇模拟费用流的题解。
思路
首先有一个抽象的费用流建模:
源点向各蓝点连
考虑反悔贪心来模拟,记红点为
先考虑有哪些要反悔:
- 非必要点
i 匹配前面的必要点j ,他可以把j 让给后面的同色必要点匹配。 - 必要点
i 匹配了前面的非必要点j ,他可以断开这次匹配与后面的异色点匹配。 - 必要点
i 匹配了前面反悔(2或3)过了一次的必要点j ,再次反悔与后面的异色点匹配。
因此考虑用堆
然后考虑考虑到点
-
1. 直接匹配前面的非必要点,这种肯定是选距离最近的异色点。 1. 从 $Q_{tp,tp}$ 里拿出来匹配。 1. 从 $Q_{tp \oplus 1,tp}$ 里拿出来匹配。 从这三种里选出代价最小的匹配,记下标为 $x$,代价为 $mn$,在 $Q_{tp,tp \oplus 1}$ 里放入 $-(x + mn)$ 用于反悔 $2,3$。 -
作为非必要点肯定是匹配前面的一个想要通过 $2,3$ 反悔的异色必要点,因此从 $Q_{tp \oplus 1,tp}$ 中拿堆顶,只有堆顶权值加 $x$ 小于 $0$ 时才能使答案变小,因此一直拿堆顶直到代价大于等于 $0$。 反悔的话就是反悔 $1$,在 $Q_{tp,tp}$ 中放入 $-x$。 -
还有一种要特殊处理,开头的时候一开始的连续相同颜色是无法向前匹配的,考虑贪心,找到第一个与
a_{1} 颜色不同的点i ,将这个点作为必要点匹配其中一个,剩下的作为非必要点匹配,反悔只有非必要点的部分需要反悔。
代码
#include<bits/stdc++.h>
#define bk(v,i) (v[v.size() - (i)])
#define all(v) v.begin(),v.end()
using namespace std;
const long long INF = 1e18 + 1;
template<typename T> inline void chkmax(T& x,T y){ ( x < y ) && ( x = y ); }
template<typename T> inline void chkmin(T& x,T y){ ( x > y ) && ( x = y ); }
const int N = 2e5 + 5;
int n;
struct node {
int x,tp;
} a[N];
long long min_total_length(std::vector<int> r, std::vector<int> b){
for(int i : r) a[++ n] = {i,0};
for(int i : b) a[++ n] = {i,1};
sort(a + 1,a + n + 1,[&](node x,node y){ return x.x < y.x; });
priority_queue<int,vector<int>,greater<int>> Q[2][2];
int fl = 0;
for(int i = 1;i <= n;i++)
if(a[i].tp != a[1].tp){ fl = i; break; }
long long ans = a[fl].x - a[1].x;
for(int i = 2;i < fl;i++)
ans += a[fl].x - a[i].x,Q[a[fl].tp][a[fl].tp].push(-a[fl].x);
int lst[2];
lst[a[fl].tp] = fl,lst[a[fl].tp ^ 1] = fl - 1;
for(int i = fl + 1;i <= n;i++){
long long op = -1,mn = INF;
auto [x,tp] = a[i];
if(x - a[lst[tp ^ 1]].x < mn){
op = 1,mn = x - a[lst[tp ^ 1]].x;
}
if(Q[tp][tp].size() && x + Q[tp][tp].top() < mn){
op = 2,mn = x + Q[tp][tp].top();
}
if(Q[tp ^ 1][tp].size() && x + Q[tp ^ 1][tp].top() < mn){
op = 3,mn = x + Q[tp ^ 1][tp].top();
}
ans += mn;
Q[tp][tp ^ 1].push(-(x + mn));
if(op == 2){
Q[tp][tp].pop();
}
else if(op == 3){
Q[tp ^ 1][tp].pop();
}
while(Q[tp ^ 1][tp].size() && x + Q[tp ^ 1][tp].top() < 0){
ans += x + Q[tp ^ 1][tp].top();
Q[tp ^ 1][tp].pop();
Q[tp][tp].push(-x);
}
lst[tp] = i;
}
return ans;
}
// int main(){
// int n,m; cin >> n >> m;
// std :: vector<int> r,b;
// for(int i = 1;i <= n;i++){
// int x; cin >> x,r.push_back(x);
// }
// for(int i = 1;i <= m;i++){
// int x; cin >> x,b.push_back(x);
// }
// cout << min_total_length(r,b) << "\n";
// }