费用流好题!学到许多。
https://www.luogu.com.cn/problem/P3358
题意
这道题题意一开始不知道为啥给我脑补成选几个区间求其并长度的最大值。。其实是给定 \(n\) 个区间,需要选取一个区间集合,使得区间覆盖的所有点被覆盖不超过 \(k\) 次,使得选取区间的总长度最大(不是并长度)。
Tutorial
可以发现如果两个区间之间不相交,那么他们俩就可以随便选。但是如果出现相交,那么他们之间就存在 \(k\) 的限制。如果将一个区间拆成两个点,容量为1,费用为区间长度,表示一个区间最多贡献一次长度。这样一来就会发现整个图变成了几组组内不会相交,但是组间会相交的区间组。就像电流的串联并联一样,接下来只要把这些区间串起来,向源点连一条容量为 \(k\) 的边,就可以限制最多重叠次数。
注意离散化。
点击查看代码
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <vector>
#define endl '\n'
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define P pair<int, int>
#define endl '\n'
using namespace std;
typedef long long ll;
const int maxn = 500 * 2 + 10;
const ll inf = 1e18;
int n1, n2, cnt_edge = 1, S, T;
int head[maxn];
ll dis[maxn];
bool vis[maxn];
struct edge {
int to, nxt;
ll flow, cost;
} e[(maxn * maxn) << 2];
inline void add(int u, int v, ll w, ll c) {
e[++cnt_edge].nxt = head[u];
head[u] = cnt_edge;
e[cnt_edge].to = v;
e[cnt_edge].flow = w;
e[cnt_edge].cost = c;
}
inline void addflow(int u, int v, ll w, ll c) {
add(u, v, w, c);
add(v, u, 0, -c);
}
inline bool spfa(int on) {
memset(vis, 0, sizeof(vis));
if (on == 1)
for (int i = 0; i <= T; i++) dis[i] = inf;
else
for (int i = 0; i <= T; i++) dis[i] = -inf;
queue<int> q;
q.push(S);
dis[S] = 0;
vis[S] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
vis[x] = 0;
for (int i = head[x]; i; i = e[i].nxt) {
int y = e[i].to;
// cout << "->" << y << endl;
if ((on == 1 && e[i].flow && dis[y] > dis[x] + e[i].cost) ||
(on == -1 && e[i].flow && dis[y] < dis[x] + e[i].cost)) {
dis[y] = dis[x] + e[i].cost;
if (!vis[y]) q.push(y), vis[y] = 1;
}
}
}
if (on == 1)
return dis[T] != inf;
else
return dis[T] != -inf;
}
ll dfs(int x, ll lim) {
vis[x] = 1;
if (x == T || lim <= 0) return lim;
ll res = lim;
for (int i = head[x]; i; i = e[i].nxt) {
int y = e[i].to;
if (dis[y] != dis[x] + e[i].cost || e[i].flow <= 0 || vis[y]) continue;
ll tmp = dfs(y, min(res, e[i].flow));
res -= tmp;
e[i].flow -= tmp;
e[i ^ 1].flow += tmp;
if (res <= 0) break;
}
return lim - res;
}
inline ll Dinic(int on) {
ll res = 0, cost = 0;
while (spfa(on)) {
ll flow = dfs(S, inf);
res += flow, cost += flow * dis[T];
}
return cost;
}
int id(int x, int y, int in) {
return 2 * ((n1 * 2 + x - 2) * (x - 1) / 2 + y - 1) + in;
}
int nn, k;
int l[maxn], r[maxn], a[maxn];
int main() {
cin >> nn >> k;
for (int i = 1; i <= nn; i++) {
cin >> l[i] >> r[i];
if (l[i] > r[i]) swap(l[i], r[i]);
a[i] = l[i], a[i + nn] = r[i];
}
sort(a + 1, a + nn * 2 + 1);
int n = unique(a + 1, 1 + a + nn * 2) - a-1;
S = n + 1, T = S + 1;
for (int i = 1; i <= nn; i++) {
int L = lower_bound(a + 1, a + 1 + n, l[i]) - a;
int R = lower_bound(a + 1, a + 1 + n, r[i]) - a;
addflow(L, R, 1, r[i] - l[i]);
}
for (int i = 1; i < n; i++) {
addflow(i, i + 1, inf, 0);
}
addflow(S, 1, k, 0);
addflow(n, T, k, 0);
// cout << "build c\n";
cout << Dinic(-1);
return 0;
}