【算法】网络流-最小费用最大流(费用流)
【题解】与方格取数2类似
在S后添加辅助点S_,限流k
每条边不能重复走,限流1
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int inf=0x3f3f3f3f,maxn=,maxN=;
struct edge{int from,v,flow,cost;}e[];
int n,m,k,tot=,first[maxN],p[maxn][maxn*],q[],d[maxN],N,S,T,S_;//梯形输入,p的第二维翻倍
long long ans;
bool vis[maxN];
void insert(int u,int v,int flow,int cost)
{
tot++;e[tot].v=v;e[tot].flow=flow;e[tot].cost=cost;e[tot].from=first[u];first[u]=tot;
tot++;e[tot].v=u;e[tot].flow=;e[tot].cost=-cost;e[tot].from=first[v];first[v]=tot;
}
bool spfa()
{
memset(d,0x3f,(N+N+)*);
memset(vis,,N+N+);
int head=,tail=;q[]=T;
vis[T]=;d[T]=;
while(head!=tail)
{
int x=q[head++];if(head>=)head=;
for(int i=first[x];i;i=e[i].from)
if(e[i^].flow&&e[i^].cost+d[x]<d[e[i].v])
{
d[e[i].v]=d[x]+e[i^].cost;
if(!vis[e[i].v])
{
vis[e[i].v]=;q[tail++]=e[i].v;
if(tail>=)tail=;
}
}
vis[x]=;
}
return d[S]<inf;
}
int dfs(int x,int a)
{
vis[x]=;
if(x==T||a==)return a;
int flow=,f;
for(int i=first[x];i;i=e[i].from)
if(!vis[e[i].v]&&d[e[i].v]+e[i].cost==d[x]&&(f=dfs(e[i].v,min(a,e[i].flow)))>)//记得判vis
{
e[i].flow-=f;//正边-,反向弧+
e[i^].flow+=f;
ans+=e[i].cost*f;
a-=f;
flow+=f;
if(a==)break;
}
return flow;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
N=;
for(int i=;i<=n;i++)
{
for(int j=;j<=m+i-;j++)
{
N++;
p[i][j]=N;
}
}
S=,S_=N+N+,T=N+N+;//N计算出来后才赋值
for(int i=;i<=n;i++)
{
for(int j=;j<=m+i-;j++)
{
int x;
scanf("%d",&x);
insert(p[i][j],p[i][j]+N,,-x);
if(i<n)
{
insert(p[i][j]+N,p[i+][j],,);
insert(p[i][j]+N,p[i+][j+],,);
}
}
}
insert(S,S_,k,);
for(int i=;i<=m;i++)insert(S_,i,,);
for(int i=;i<=m+n-;i++)insert(p[n][i]+N,T,,);
ans=;
while(spfa())
{
// for(int i=0;i<=N+N+2;i++)printf("[%d]%d\n",i,d[i]);
memset(vis,,N+N+);
dfs(S,inf);
}
printf("%lld",-ans);
return ;
}