跳到正文

剪贴板

剪贴板 5qxsxp7s

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <bits/stdc++.h>
using namespace std;
#define inf 1000000000000000
#define V 100100
#define E 500100
typedef long long int ll;
struct edge {
	int to, next;
	ll capa, cost;
};
int cnt = 0, head[V], n, m; edge node[E];
inline void add(int fir, int nxt, ll w, ll c) {
	node[cnt].to = nxt,
	node[cnt].capa = w,
	node[cnt].cost = c,
	node[cnt].next = head[fir],
	head[fir] = cnt++;
}
int s, t, cur[V]; deque<int>que; ll dep[V], sum = 0, cost = 0;
bool vis[V];
inline bool spfa(){
	for(register int i = 1; i <= t; ++i)dep[i]=inf;
	dep[s] = 0; que.push_back(s); int u, v;
	while(!que.empty()){
		v = que.front(); que.pop_front();
		for(register int i = head[v]; i != -1; i = node[i].next){
			u = node[i].to;
			if(dep[v] + node[i].cost < dep[u] && node[i].capa){
				dep[u] = dep[v] + node[i].cost;
				if(!que.empty() && dep[u]<dep[que.front()])que.push_front(u);
				else que.push_back(u);
			}
		}
	}
	return (dep[t] != inf);
}
ll dfs(register int v,register ll flow){
	if(flow == 0 || v == t)return flow; ll used = 0, wei = 0;
	vis[v]=true;
	for(register int i = cur[v]; i != -1; i = node[i].next){
		cur[v] = i;
		if(!vis[node[i].to] && dep[node[i].to] == dep[v] + node[i].cost && node[i].capa){
			wei = dfs(node[i].to, min(flow - used, node[i].capa));
			if(wei){
				node[i].capa -= wei,
				node[i ^ 1].capa += wei,
				used += wei,
				cost += node[i].cost * wei;
			}
		}
		if(used == flow)break;
	}
	vis[v] = false;
	return used;
}
inline void Dinic(){
	while(spfa()){
		memcpy(cur, head, (t + 1) * sizeof(int));
		sum += dfs(s, inf);
	}
}
inline void addE(int u, int v, ll w, ll c){
	add(u, v, w, c);
	add(v, u, 0, -c);
}
ll l[V], r[V], len[V], a[V];
int main() {
	ios::sync_with_stdio(0);
	cin.tie(); cout.tie();
	memset(head, -1, V * sizeof(int));
	ll k;
	cin >> n >> k;
	for(int i = 1; i <= n; i++){
		cin >> l[i] >> r[i];
		a[i] = l[i], a[i + n] = r[i];
		len[i] = r[i] - l[i];
	}
	sort(a + 1, a + 1 + n * 2);
	int N = unique(a + 1, a + 1 + n * 2) - a - 1;
	s = N + 1, t = N + 2;
	addE(s, 1, k, 0), addE(N, t, k, 0);
	for(int i = 1; i < N; i++)addE(i, i + 1, k, 0);
	int L, R;
	for(int i = 1; i <= n; i++){
		L = lower_bound(a + 1, a + 1 + N, l[i]) - a;
		R = lower_bound(a + 1, a + 1 + N, r[i]) - a;
		addE(L, R, 1, -len[i]);
	}
	Dinic();
	cout << -cost;
	return 0;
}