首页 技术 正文
技术 2022年11月9日
0 收藏 890 点赞 2,415 浏览 1615 个字

【算法】网络流-最小费用最大流(费用流)

【题解】与方格取数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 ;
}
上一篇: HTML入门(一)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295