最长k可重区间集问题(费用流)

//http://www.cnblogs.com/IMGavin/
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <bitset>
#include <algorithm>
using namespace std;

typedef long long LL;
#define gets(A) fgets(A, 1e8, stdin)
const int INF = 0x3F3F3F3F, N = 1008, MOD = 1003, M = 1000000;


int l[N], r[N], a[N];
const double EPS = 1e-6;
struct Node{
	int u, v, cap, cost;
	int next;
}edge[M];//有向图,u到v的容量,费用
int tot;
int head[N], pre[N], path[N], dis[N];
bool inq[N];

void init(){
	tot = 0;
	memset(head, -1, sizeof(head));
}

void add(int u, int v, int cap, int cost){
	edge[tot].u = u;
	edge[tot].v = v;
	edge[tot].cap = cap;
	edge[tot].cost = cost;
	edge[tot].next = head[u];
	head[u] = tot++;
	edge[tot].u = v;
	edge[tot].v = u;
	edge[tot].cap = 0;
	edge[tot].cost = -cost;
	edge[tot].next = head[v];
	head[v] = tot++;
}

bool SPFA(int st, int des){//计算最小费用
	memset(inq, 0, sizeof(inq));
	memset(dis, 0x3f, sizeof(dis));
	queue <int> q;
	q.push(st);
	dis[st] = 0;
	inq[st] = true;
	while(!q.empty()){
		int u = q.front();
		q.pop();
		inq[u] = false;
		for(int i = head[u]; ~i; i = edge[i].next){
			int v = edge[i].v;
			if(edge[i].cap > 0 && dis[v] > dis[u] + edge[i].cost){
				dis[v] = dis[u] + edge[i].cost;
				pre[v] = u;
				path[v] = i;
				if(!inq[v]){
					inq[v] = true;
					q.push(v);
				}
			}
		}
	}
	return dis[des] < INF;
}

int EdmondsKarp(int st, int des){//最小费用最大流
	int mincost = 0, flow = 0;//最小费用与流量
	while(SPFA(st, des)){
		int f = INF;
		for(int i = des; i != st; i = pre[i]){
            if(f > edge[path[i]].cap){
                f = edge[path[i]].cap;
            }
		}
		for(int i = des; i != st; i = pre[i]){
			edge[path[i]].cap -= f;
			edge[path[i]^1].cap += f;
		}
		mincost += f * dis[des];
		flow += f;
	}
	return mincost;
}
int main(){
	
	int n, k;
	while(cin >> n >> k){
		int num = 0;
		for(int i = 0; i < n; i++){
			scanf("%d %d", &l[i], &r[i]);
			a[num++] = l[i];
			a[num++] = r[i];
		}


		sort(a, a + num);
		num = unique(a, a + num) - a;
		init();
		int st = 0, des = num + 1;
		add(st, 1, k, 0);
		add(num, des, k, 0);
		for(int i = 0; i < n; i++){
			int u = lower_bound(a, a + num, l[i]) - a + 1;
			int v = lower_bound(a, a + num, r[i]) - a + 1;
			add(u, v, 1, l[i] - r[i]);
		}
		for(int i = 0; i < num - 1 ;i++){
			add(i + 1, i + 2, INF, 0);
		}
		printf("%d\n", -EdmondsKarp(st, des));

	}

	return 0;
}

  

转载于:https://www.cnblogs.com/IMGavin/p/6412714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值