题目链接
题意
x0y平面上n条开线段,求一个线段子集,使得它的线段长度和最长,且对于每条垂直于x轴的线段都不超过k条线段与之相交。
思路
类似最长k可重区间集问题,因为只对x轴上的点有限制,一样的,离散化后建边,跑最大费用最大流,需要注意的是这里是开线段,有个神奇的处理就是把l改为l * 2+1,r改为r * 2。先对x离散化,处理出费用,也就是线段的长度,对于每个相邻的点连上容量为INF,费用为0的边,对于每一条线段,左端点与右端点连上容量为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 l[maxn], r[maxn], w[maxn], a[maxn];
int main()
{
int n, m, s, t, k;
scanf("%d%d", &n, &k);
MCMF solve;
int tot = 0;
for (int i = 1; i <= n; i++) {
int x1, x2, y1, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
w[i] = sqrt((ll)(x1 - x2) * (x1 - x2) + (ll)(y1 - y2) * (y1 - y2));
l[i] = x1<<1|1, r[i] = x2<<1;
a[++tot] = l[i], a[++tot] = r[i];
if(l[i] > r[i]) swap(l[i], r[i]);
}
sort(a + 1, a + 1 + tot);
tot = unique(a + 1, a + 1 + tot) - a - 1;
s = 0; t = 1001;
solve.add(s, 1, k, 0); solve.add(tot, t, k, 0);
for (int i = 1; i <= n; i++) {
int x = lower_bound(a + 1, a + 1 + tot, l[i]) - a;
int y = lower_bound(a + 1, a + 1 + tot, r[i]) - a;
solve.add(x, y, 1, -w[i]);
}
for (int i = 1; i < tot; i++) solve.add(i, i + 1, INF, 0);
printf("%d\n", -solve.MinMaxflow(s, t));
}