传送门:点击打开链接
题意:给你n个开区间,每个区间有权值,现在每个点最多只能被覆盖k次,选择多个区间,使权值最大。
思路:先将坐标离散化
然后建图,将源点连到1,n连到汇点,容量都是k,费用为0
然后将线段中每两个相邻的点都连接一条容量为k费用为0的边,让流量能从左边抵达右边
对于每一个区间,建一条边从L流向R容量为1费用为-W
这样建图,就算一个点被区间覆盖了很多次,但是由于区间的最右边总会把流量汇集到一个点,但是想通过这个点,流量必须控制在k以内,所以之前的点最多也只会被覆盖k次了~
#include<map>
#include<set>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w+",stdout)using namespace std;
typedef long long LL;
typedef pair<int, int> PII;const int MX = 10000 + 5;//都开4倍把..
const int MM = 10000 + 5;
const int INF = 0x3f3f3f3f;struct Edge {int to, next, cap, flow, cost;Edge() {}Edge(int _to, int _next, int _cap, int _flow, int _cost) {to = _to; next = _next; cap = _cap; flow = _flow; cost = _cost;}
} E[MM];int Head[MX], tol;
int pre[MX]; //储存前驱顶点
int dis[MX]; //储存到源点s的距离
bool vis[MX];
int N;//节点总个数,节点编号从0~N-1void init(int n) {tol = 0;N = n + 2;memset(Head, -1, sizeof(Head));
}
void edge_add(int u, int v, int cap, int cost) {E[tol] = Edge(v, Head[u], cap, 0, cost);Head[u] = tol++;E[tol] = Edge(u, Head[v], 0, 0, -cost);Head[v] = tol++;
}
bool spfa(int s, int t) {queue<int>q;for (int i = 0; i < N; i++) {dis[i] = INF;vis[i] = false;pre[i] = -1;}dis[s] = 0;vis[s] = true;q.push(s);while (!q.empty()) {int u = q.front();q.pop();vis[u] = false;for (int i = Head[u]; i != -1; i = E[i].next) {int v = E[i].to;if (E[i].cap > E[i].flow && dis[v] > dis[u] + E[i].cost) {dis[v] = dis[u] + E[i].cost;pre[v] = i;if (!vis[v]) {vis[v] = true;q.push(v);}}}}if (pre[t] == -1) return false;else return true;
}//返回的是最大流, cost存的是最小费用
int minCostMaxflow(int s, int t, int &cost) {int flow = 0;cost = 0;while (spfa(s, t)) {int Min = INF;for (int i = pre[t]; i != -1; i = pre[E[i ^ 1].to]) {if (Min > E[i].cap - E[i].flow)Min = E[i].cap - E[i].flow;}for (int i = pre[t]; i != -1; i = pre[E[i ^ 1].to]) {E[i].flow += Min;E[i ^ 1].flow -= Min;cost += E[i].cost * Min;}flow += Min;}return flow;
}int A[MX], rear;
int L[MX], R[MX], W[MX];int BS(int x) {int l = 1, r = rear, m;while(l <= r) {m = (l + r) >> 1;if(A[m] == x) return m;if(A[m] < x) l = m + 1;else r = m - 1;}return -1;
}int main() {int T, n, k;//FIN;scanf("%d", &T);while(T--) {rear = 0;scanf("%d%d", &n, &k);for(int i = 1; i <= n; i++) {scanf("%d%d%d", &L[i], &R[i], &W[i]);A[++rear] = L[i]; A[++rear] = R[i];}sort(A + 1, A + 1 + rear);rear = unique(A + 1, A + 1 + rear) - A - 1;int s = 0, t = rear + 1;init(t);edge_add(s, 1, k, 0);edge_add(rear, t, k, 0);for(int i = 1; i < rear; i++) {edge_add(i, i + 1, k, 0);}for(int i = 1; i <= n; i++) {edge_add(BS(L[i]), BS(R[i]), 1, -W[i]);}int ans = 0;minCostMaxflow(s, t, ans);printf("%d\n", -ans);}return 0;
}