https://nanti.jisuanke.com/t/A2016
思路:和这道题基本上一样:https://blog.csdn.net/xiji333/article/details/104010374
唯一的区别就是区间从左闭右开变成了左右均闭,在处理的时候把右端点
就好了。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;const int maxn=410;
const int maxm=2005;struct Edge
{int to,nxt,dis,f;
}edge[maxm<<1];int n,m,s,t,k,tot;
int head[maxn],dis[maxn],vis[maxn],pre[maxn],maxf[maxn];
int l[maxn],r[maxn],a[maxn],b[maxn]; //用于离散化inline void addedge(int u,int v,int f,int dis)
{edge[++tot].to=v,edge[tot].nxt=head[u],edge[tot].f=f,edge[tot].dis=dis,head[u]=tot;edge[++tot].to=u,edge[tot].nxt=head[v],edge[tot].f=0,edge[tot].dis=-dis,head[v]=tot;
}bool spfa()
{memset(dis,INF,sizeof(dis));queue<int> q;dis[s]=0,vis[s]=1,maxf[s]=INF;q.push(s);while(!q.empty()){int u=q.front();q.pop();vis[u]=0;for(int i=head[u];i;i=edge[i].nxt){int v=edge[i].to;if(edge[i].f&&dis[v]>dis[u]+edge[i].dis){dis[v]=dis[u]+edge[i].dis;pre[v]=i;maxf[v]=min(maxf[u],edge[i].f);if(!vis[v])q.push(v),vis[v]=1;}}}return dis[t]!=INF;
}int MCMF()
{int mcost=0;while(spfa()){int u=t,v;while(u!=s){v=pre[u];edge[v].f-=maxf[t];edge[v^1].f+=maxf[t];u=edge[v^1].to;}mcost+=dis[t]*maxf[t];}return -mcost;
}int main()
{int T;scanf("%d",&T);while(T--){scanf("%d %d %d",&n,&k,&m);memset(head,0,sizeof(head));tot=1;int len=0;for(int i=0;i<m;i++){scanf("%d %d %d",&l[i],&r[i],&a[i]);b[++len]=l[i],b[++len]=r[i];}sort(b+1,b+len+1);len=unique(b+1,b+len+1)-b-1;s=0,t=len+1;for(int i=0;i<=len;i++)addedge(i,i+1,k,0);for(int i=0;i<m;i++){l[i]=lower_bound(b+1,b+len+1,l[i])-b;r[i]=lower_bound(b+1,b+len+1,r[i])-b;addedge(l[i],r[i]+1,1,-a[i]); //因为是左右均闭}printf("%d\n",MCMF());}return 0;
}