题目链接
题意
给n个区间的集合S,求一个区间集合A属于S,且集合A的每个区间的长度和最大,每个点最多可以选k次。
思路
首先每个点可以重复k次,可以用流量来限制,用最大费用最大流来做。
将所有区间离散化,源点在最左边,汇点在最右边,每一个点都向右边相邻的点连一条容量为INF,费用为0的边,对于每个区间,左端点到右端点连一条容量为1费用为r-l的边,容量为1是因为一个区间只能取一次。然后跑最大费用最大流。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 5e3 + 7;
const int M = 1e4 + 7;
const int maxn = 5e3 + 7;
typedef long long ll;
int maxflow, mincost;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int ca, int f, int co):from(u), to(v), cap(ca), flow(f), cost(co){};
};
struct MCMF
{
int n, m, s, t;
vector<Edge> edges;
vector<int> G[N];
int inq[N], d[N], p[N], a[N];//是否在队列 距离 上一条弧 可改进量
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void add(int from, int to, int cap, int cost) {
edges.push_back(Edge(from, to, cap, 0, cost));
edges.push_back(Edge(to, from, 0, 0, -cost));
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool SPFA(int s, int t, int &flow, int &cost) {
for (int i = 0; i < N; i++) d[i] = INF;
memset(inq, 0, sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
inq[u]--;
for (int i = 0; i < G[u].size(); i++) {
Edge& e = edges[G[u][i]];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if(!inq[e.to]) {
inq[e.to]++;
que.push(e.to);
}
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int MinMaxflow(int s, int t) {
int flow = 0, cost = 0;
while (SPFA(s, t, flow, cost));
maxflow = flow; mincost = cost;
return cost;
}
};
int a[maxn], l[maxn], r[maxn], tot;
int main()
{
int n, m, s, t, k;
scanf("%d%d", &n, &k);
MCMF solve;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &l[i], &r[i]);
if(l[i] > r[i]) swap(l[i], r[i]);
a[++tot] = l[i], a[++tot] = r[i];
}
sort(a + 1, a + 1 + tot);
int siz = unique(a + 1, a + 1 + tot) - a - 1;
for (int i = 1; i <= n; i++) {
l[i] = lower_bound(a + 1, a + 1 + siz, l[i]) - a;
r[i] = lower_bound(a + 1, a + 1 + siz, r[i]) - a;
}
s = 0; t = siz + 1;
solve.add(s, 1, k, 0);
solve.add(siz, t, k, 0);
for (int i = 1; i < siz; i++) solve.add(i, i + 1, INF, 0);
for (int i = 1; i <= n; i++) solve.add(l[i], r[i], 1, a[l[i]] - a[r[i]]);
solve.MinMaxflow(s, t);
printf("%d\n", -mincost);
}