题目大意:
给你一些开区间,让你选择一些区间(开区间),使得没有一个数字出现的次数超过k次的情况下,获得的价值最大。
分析:
首先将输入的区间离散化,之后对于相邻的节点,连一条容量为INF,费用为0的边,之后对于每一个区间,加一条容量为1,花费为-的w[i]的边。源点和1之间建立一条容量为k,花费为0的边,在m与汇点间建立一条容量为k的边。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 400 + 10;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from,to,cap,flow,cost;
};
struct MCMF
{
int n,m,s,t;
vector<Edge>edges;
vector<int>G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<=n;i++) G[i].clear();
edges.clear();
}
void addedge(int from,int to,int cap,int cost)
{
edges.push_back((Edge){from,to,cap,0,cost});
edges.push_back((Edge){to,from,0,0,-cost});
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(int s,int t,int &flow,int& cost)
{
for(int i=0;i<=n;i++) d[i]=INF;
memset(inq,0,sizeof(inq));
d[s]=0;
inq[s]=1; p[s]=0; a[s]=INF;
queue<int>Q;
Q.push(s);
while(!Q.empty())
{
int u=Q.front(); Q.pop();
inq[u]=0;
for(int i=0;i<G[u].size();i++)
{
Edge &e=edges[G[u][i]];
if(e.cap>e.flow&&d[e.to]>d[u]+e.cost)
{
d[e.to]=d[u]+e.cost;
p[e.to]=G[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if(!inq[e.to]) {Q.push(e.to); inq[e.to]=1;}
}
}
}
if(d[t]==INF) return false;
flow+=a[t];
cost+=d[t]*a[t];
int u=t;
while(u!=s)
{
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return true;
}
int Mincost(int s,int t)
{
int flow=0,cost=0;
while(BellmanFord(s,t,flow,cost));
return cost;
}
}D;
int temp[maxn];
struct node
{
int x,y,z;
}s[maxn];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,k;
scanf("%d%d",&n,&k);
int cnt=0;
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&s[i].x,&s[i].y,&s[i].z);
temp[cnt++]=s[i].x;
temp[cnt++]=s[i].y;
}
sort(temp,temp+cnt);
int m=unique(temp,temp+cnt)-temp;
int s_=0,t=m+1;
D.init(m+1);
for(int i=1;i<m;i++)
D.addedge(i,i+1,INF,0);
D.addedge(s_,1,k,0); D.addedge(m,t,k,0);
for(int i=0;i<n;i++)
{
//int x=s[i].x;
int u=lower_bound(temp,temp+m,s[i].x)-temp;
int v=lower_bound(temp,temp+m,s[i].y)-temp;
D.addedge(u+1,v+1,1,-s[i].z);
}
int ans = D.Mincost(s_,t);
printf("%d\n",-ans);
}
return 0;
}