题目:
http://poj.org/problem?id=3680
题意:
给定n个区间,类似于(a,b),每个区间有一个价值,现在可以取任意个区间,但每个区间只能取一次,又要求数轴上的每个实数点被选取不超过k次,求这些约束条件下可以得到的最大价值
思路:
首先对区间端点进行离散化,用离散后的端点进行建图。对于某个区间(a,b),建边a->b,容量为1,费用为此区间的价值,这样意味着每个区间只能被选一次。另外对于离散化后的端点,从源点向第一个点连边,容量为k费用为0,从最后一个点向汇点连边,容量为k费用为0,然后相邻的两点i和i+1,连边i->i+1,容量大于等于k费用为0,这样建图的话,可以发现对于一个流量为1的流,选取的区间一定不会发生重叠,于是最多选取k次,满足题意要求。最后直接输出费用流结果即可
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 410;
const int INF = 0x3f3f3f3f;
struct edge
{
int st, to, cap, cost, next;
}g[N*N*4];
int cas;
int cnt, head[N];
int dis[N], pre[N];
bool vis[N];
void add_edge(int v, int u, int cap, int cost)
{
g[cnt].st = v, g[cnt].to = u, g[cnt].cap = cap, g[cnt].cost = cost, g[cnt].next = head[v], head[v] = cnt++;
g[cnt].st = u, g[cnt].to = v, g[cnt].cap = 0, g[cnt].cost = -cost, g[cnt].next = head[u], head[u] = cnt++;
}
void spfa(int s, int t)
{
memset(dis, 0x3f, sizeof dis);
memset(vis, 0, sizeof vis);
memset(pre, -1, sizeof pre);
queue<int> que;
que.push(s);
dis[s] = 0, vis[s] = true;
while(! que.empty())
{
int v = que.front(); que.pop();
vis[v] = false;
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && dis[u] > dis[v] + g[i].cost)
{
dis[u] = dis[v] + g[i].cost;
pre[u] = i;
if(! vis[u])
que.push(u), vis[u] = true;
}
}
}
}
int cost_flow(int s, int t, int flow)
{
int res = 0;
while(flow > 0)
{
spfa(s, t);
if(dis[t] == INF) return -1;
int d = flow;
for(int i = pre[t]; i != -1; i = pre[g[i].st])
d = min(d, g[i].cap);
for(int i = pre[t]; i != -1; i = pre[g[i].st])
g[i].cap -= d, g[i^1].cap += d;
flow -= d;
res += d * dis[t];
}
return res;
}
int main()
{
int t, n, k;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &k);
int a[N], b[N], c[N], tm[N*2], tot = 0;
for(int i = 1; i <= n; i++)
{
scanf("%d%d%d", &a[i], &b[i], &c[i]);
tm[tot++] = a[i], tm[tot++] = b[i];
}
sort(tm, tm + tot);
tot = unique(tm, tm + tot) - tm;
cnt = 0;
memset(head, -1, sizeof head);
int ss = 0, tt = tot + 1;
add_edge(ss, 1, k, 0);
add_edge(tot, tt, k, 0);
for(int i = 2; i <= tot; i++) add_edge(i-1, i, INF, 0);
for(int i = 1; i <= n; i++)
{
int v = lower_bound(tm, tm + tot, a[i]) - tm + 1;
int u = lower_bound(tm, tm + tot, b[i]) - tm + 1;
add_edge(v, u, 1, -c[i]);
}
printf("%d\n", -cost_flow(ss, tt, k));
}
return 0;
}