版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40924940/article/details/84311318
一道最大流最小费用摸板题。。
此处开始学习了最小费用,首先还是以最短路的思路去搞(此处用的 spfa)来判断给定起点终点后能否到达最终目标点
当然首先是熟悉的建连通图环节:
struct edge
{
int to,next;
int flow,dis;
}ed[maxn];
int head[maxn],num;
num = -1;
void inset(int from, int to, int flow, int dis)
{
ed[++num].next=head[from];
ed[num].to=to;
ed[num].flow=flow;
ed[num].dis=dis;
head[from]=num;
}
//dis 代表距离 flow 代表容量
之后 就是我们的 spfa 环节了这里 spfa 用来判断能否到达终点同时记录下路线和容量、距离等数据
int n,m,s,t;
int x,y,z,f ;
int dis[maxn],pre[maxn];
int vis[maxn],flo[maxn];
int last[maxn];
bool spfa(int s,int t)
{
memset(dis,INF,sizeof(dis));//全部设置成无穷大
memset(flo,INF,sizeof(flo));//在起始的时候
memset(vis,0,sizeof(vis));//重置拜访数组
queue<int> q;
q.push(s);
vis[s]=1; dis[s]=0; pre[t]=-1;
while (q.size())//开始跑一半 spfa
{
int now=q.front();
q.pop();
vis[now]=0;
for (int i=head[now]; i!=-1; i=ed[i].next)//运用我们建立的连通图
{
if (ed[i].flow>0 && dis[ed[i].to]>dis[now]+ed[i].dis)//容量足够且距离可以松弛时
{
dis[ed[i].to]=dis[now]+ed[i].dis;//松弛操作
pre[ed[i].to]=now;//记录父节点
last[ed[i].to]=i;//记录下标
flo[ed[i].to]=min(flo[now],ed[i].flow);//储存容量
if (!vis[ed[i].to])
{
vis[ed[i].to]=1;
q.push(ed[i].to);
}
}
}
}
return pre[t]!=-1;//判断终点是否能够到达
}
最后 进行我们的最终判断,
void MCMF()
{
while(spfa(s,t))
{
int now=t;
maxflow+=flo[t]; // 最大流记录一下
mincost+=flo[t]*dis[t]; // 最小距离记录一下
while (now!=s)
{
ed[last[now]].flow-=flo[t]; //更新一下流量
ed[last[now]^1].flow+=flo[t];//相邻的边就是反向边了
now=pre[now];//向上遍历
}
}
}
有了这几步,我们就可以把这道摸板题搞定了。。。
以下为 AC 代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1e5+5;
const int INF = 0x3f3f3f3f;
int n,m,s,t;
int x,y,z,f ;
int dis[maxn],pre[maxn];
int vis[maxn],flo[maxn];
int last[maxn];
int maxflow,mincost;
struct edge
{
int to,next;
int flow,dis;
}ed[maxn];
int head[maxn],num;
void inset(int from, int to, int flow, int dis)
{
ed[++num].next=head[from];
ed[num].to=to;
ed[num].flow=flow;
ed[num].dis=dis;
head[from]=num;
}
bool spfa(int s,int t)
{
memset(dis,INF,sizeof(dis));
memset(flo,INF,sizeof(flo));
memset(vis,0,sizeof(vis));
queue<int> q;
q.push(s); vis[s]=1; dis[s]=0; pre[t]=-1;
while (!q.empty())
{
int now=q.front();
q.pop();
vis[now]=0;
for (int i=head[now]; i!=-1; i=ed[i].next)
{
if (ed[i].flow>0 && dis[ed[i].to]>dis[now]+ed[i].dis)
{
dis[ed[i].to]=dis[now]+ed[i].dis;
pre[ed[i].to]=now;
last[ed[i].to]=i;
flo[ed[i].to]=min(flo[now],ed[i].flow);
if (!vis[ed[i].to])
{
vis[ed[i].to]=1;
q.push(ed[i].to);
}
}
}
}
return pre[t]!=-1;
}
void MCMF()
{
while(spfa(s,t))
{
int now=t;
maxflow+=flo[t];
mincost+=flo[t]*dis[t];
while (now!=s)
{
ed[last[now]].flow-=flo[t];
ed[last[now]^1].flow+=flo[t];
now=pre[now];
}
}
}
int main()
{
memset(head,-1,sizeof(head));num=-1;
scanf("%d%d%d%d",&n,&m,&s,&t);
for (int i=1; i<=m; i++)
{
scanf("%d%d%d%d",&x,&y,&z,&f);
inset(x,y,z,f);
inset(y,x,0,-f);
}
MCMF();
printf("%d %d",maxflow,mincost);
return 0;
}