这道题建图过程很巧妙。先附上大佬博客Orz:
https://www.cnblogs.com/xingxing1024/p/5490293.html
这道题我一开始想的是拆点,把点的限制转换为边的限制;但是后来发现这并不能限制点的“经过次数”,怎么改都不对QAQ...后来看了大佬的博客,才知道这原来是一类经典题。。我好菜啊啊啊55555...另外要注意这是开区间,如果是闭区间修改v=v+1即可。
建图果然是门艺术啊QAQ...
附上AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=205*2;
const int MAXM=205*2;
struct Edge
{
int to,next;
int cap,flow,cost;
}edge[4*MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;
void init(int n)
{
N=n;
tol=0;
memset(head,-1,sizeof(head));
memset(edge,0,sizeof(edge));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].to=v;edge[tol].cap=cap;edge[tol].cost=cost;
edge[tol].flow=0;edge[tol].next=head[u];head[u]=tol++;
edge[tol].to=u;edge[tol].cap=0;edge[tol].cost=-cost;
edge[tol].flow=0;edge[tol].next=head[v];head[v]=tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i=0;i<N;i++)
{
dis[i]=INF;
vis[i]=false;
pre[i]=-1;
}
dis[s]=0;
vis[s]=true;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=false;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(edge[i].cap>edge[i].flow&&dis[v]>dis[u]+edge[i].cost)
{
dis[v]=dis[u]+edge[i].cost;
pre[v]=i;
if(!vis[v])
{
vis[v]=true;
q.push(v);
}
}
}
}
if(dis[t]==INF)
return false;
else
return true;
}
int MincostMaxflow(int s,int t,int &cost)
{
int flow=0;
cost=0;
while(spfa(s,t))
{
int Min=INF;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to])
if(Min>edge[i].cap-edge[i].flow)
Min=edge[i].cap-edge[i].flow;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to])
{
edge[i].flow+=Min;
edge[i^1].flow-=Min;
cost+=edge[i].cost*Min;
}
flow+=Min;
}
return flow;
}
struct path
{
int u,v,w;
}p[205];
int main()
{
int n,m,k;
int t;
scanf("%d",&t);
int tmp[MAXN];
while(t--)
{
scanf("%d%d",&m,&k);
memset(tmp,0,sizeof(tmp));
memset(p,0,sizeof(p));
//离散化
int to=0;
int u,v,w;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
p[i].u=u;p[i].v=v;p[i].w=w;
tmp[++to]=u;tmp[++to]=v;
}
sort(tmp+1,tmp+1+to);
int tot=unique(tmp+1,tmp+1+to)-tmp-1;
//cout<<"to="<<to<<" tot="<<tot<<endl;
//建图
int s=0,t=tot+1;
init(tot+2);
addedge(s,1,k,0);
addedge(tot,t,k,0);
for(int i=1;i<tot;i++)
addedge(i,i+1,k,0);
for(int i=1;i<=m;i++)
{
u=lower_bound(tmp+1,tmp+1+tot,p[i].u)-tmp;
v=lower_bound(tmp+1,tmp+1+tot,p[i].v)-tmp;
//cout<<"u="<<u<<" v="<<v<<" w="<<p[i].w<<endl;
addedge(u,v,1,-p[i].w);
}
int ans,cost=0;
ans=MincostMaxflow(s,t,cost);
//cout<<"ans="<<ans<<" cost="<<cost<<endl;
printf("%d\n",-cost);
}
return 0;
}