//建图还是很好的,离散化我要注意了。
//建图如下
//
//若限制为k
//
//首先将坐标离散化。
//
//对每个区间,左端点对应的编号到右端点对应的编号建一条边,容量为k,费用为负权
//
//然后对每个编号i,建立i到i+1的边,容量为k,费用为0
//
//起点和编号1连边,容量为k,费用0
//
//最后一个编号和终点连边,容量为k,费用0
//
//然后跑费用流即可
//我觉得这题和对费用流算法的理解有关系,图中有容量无费用边,他会先跑掉。!!!
//建图超级好。
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<queue>
#define maxn 201000
using namespace std;
int sumFlow;
const int MAXN = 1010;
const int MAXM = 1000200;
const int INF = 1000000000;
struct Edge
{
int u, v, cap, cost;
int next;
}edge[MAXM<<2];
int NE;
int head[MAXN], dist[MAXN], pp[MAXN];
bool vis[MAXN];
void init()
{
NE = 0;
memset(head, -1, sizeof(head));
}
void addedge(int u, int v, int cap, int cost)
{
// cout<<u<<" "<<v<<" "<<cap<<" "<<cost<<endl;
edge[NE].u = u; edge[NE].v = v; edge[NE].cap = cap; edge[NE].cost = cost;
edge[NE].next = head[u]; head[u] = NE++;
edge[NE].u = v; edge[NE].v = u; edge[NE].cap = 0; edge[NE].cost = -cost;
edge[NE].next = head[v]; head[v] = NE++;
}
bool SPFA(int s, int t, int n)
{
int i, u, v;
queue <int> qu;
memset(vis,false,sizeof(vis));
memset(pp,-1,sizeof(pp));
for(i = 0; i <= n; i++) dist[i] = INF;
vis[s] = true; dist[s] = 0;
qu.push(s);
while(!qu.empty())
{
u = qu.front(); qu.pop(); vis[u] = false;
for(i = head[u]; i != -1; i = edge[i].next)
{
v = edge[i].v;
if(edge[i].cap && dist[v] > dist[u] + edge[i].cost)
{
dist[v] = dist[u] + edge[i].cost;
pp[v] = i;
if(!vis[v])
{
qu.push(v);
vis[v] = true;
}
}
}
}
if(dist[t] == INF) return false;
return true;
}
int MCMF(int s, int t, int n) /// minCostMaxFlow
{
// cout<<s<<" "<<t<<" "<<n<<endl;
int flow = 0; /// 总流量
int i, minflow, mincost;
mincost = 0;
while(SPFA(s, t, n))
{
// cout<<"mi "<<endl;
minflow = INF + 1;
for(i = pp[t]; i != -1; i = pp[edge[i].u])
if(edge[i].cap < minflow)
minflow = edge[i].cap;
flow += minflow;
for(i = pp[t]; i != -1; i = pp[edge[i].u])
{
edge[i].cap -= minflow;
edge[i^1].cap += minflow;
}
mincost += dist[t] * minflow;
}
sumFlow = flow; /// 最大流
return mincost;
}
///讨厌的从0开始的点
///费用流板子。。
int miss[maxn];
struct node
{
int a,b;
}line[maxn];
int lin[maxn];
int main()
{
int cas;
int n,k;
scanf("%d",&cas);
for(int ca=1;ca<=cas;ca++)
{
init();
scanf("%d%d",&n,&k);
int cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d%d",&line[i].a,&line[i].b,&miss[i]);
lin[cnt++]=line[i].a;
lin[cnt++]=line[i].b;
}
sort(lin,lin+cnt);
cnt=unique(lin,lin+cnt)-lin;
for(int i=1;i<=n;i++)
{
int x=lower_bound(lin,lin+cnt,line[i].a)-lin+1;
int y=lower_bound(lin,lin+cnt,line[i].b)-lin+1;
addedge(x,y,1,-miss[i]);
}
for(int i=1;i<cnt;i++)
addedge(i,i+1,k,0);
int src=0;
int dest=cnt+1;
addedge(src,1,k,0);
addedge(cnt,dest,k,0);
int ans=MCMF(src,dest,cnt+2);
// cout<<ans<<endl;
cout<<-ans<<endl;
}
}
POJ 3680 费用流加离散化
最新推荐文章于 2018-12-22 20:43:00 发布