算法实现过程:
1,每次查找是否 存在源点到汇点的可增广路径,并用pre[ i ]记录路径上到达点i 的 边 的编号。这里的路径指的是 —— 源点到汇点的最短路(边权为费用) 且 路径上所有边都不能满流;
2,若存在这样的路径,从汇点沿着pre数组向前找,找到该路径上可以增广的流量Min(当然是所有边中剩余流量最小的)。再从汇点遍历一次,正向边增加流量Min,反向边减少Min,总费用累加Min * edge[i].cost,总流量累加Min。
//最小费用最大流模板,SPFA实现
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
#define inf 0x3f3f3f3f
#define maxn 100005
using namespace std;
int n, m; //结点数, 边数
int edgenum;
int head[maxn]; //链式前向星需要用到的数组
int vis[maxn]; //记录一个点是否在队列中
int dist[maxn]; //记录最短路
int pre[maxn]; //记录前驱边
struct Edge
{
int from, to, cap, flow, cost, next; //起点, 终点,容量, 流量,单位流量的费用,连接的下一条边
}edge[maxn];
//初始化
void init()
{
edgenum = 0;
memset(edge, 0, sizeof(edge));
memset(head, -1, sizeof(head)); //因为边数是从0开始,所以初始化为-1
}
//加边(注意反向边)
void add_edge(int u, int v, int cap, int cost)
{
Edge E1 = {u, v, cap, 0, cost, head[u]};
edge[edgenum] = E1;
head[u] = edgenum++;
Edge E2 = {v, u, 0, 0, -cost, head[v]};
edge[edgenum] = E2;
head[v] = edgenum++;
}
//建图
void creat_graph()
{
for(int i=0; i<m; i++)
{
int u, v, cap, cost;
scanf("%d%d%d%d", &u, &v, &cap, &cost);
add_edge(u, v, cap, cost);
}
}
//寻找最短路径(即最小费用)
bool SPFA(int s, int t)
{
memset(dist, inf, sizeof(dist));
memset(vis, 0, sizeof(vis));
memset(pre, -1, sizeof(pre));
queue<int>q;
q.push(s);
vis[s] = 1;
dist[s] = 0;
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(int i=head[u]; i!=-1; i=edge[i].next)
{
Edge e = edge[i];
if(dist[e.to] > dist[u] + e.cost && e.cap>e.flow) //可松弛
{
dist[e.to] = dist[u] + e.cost;
pre[e.to] = i;
if(!vis[e.to])
{
vis[e.to] = 1;
q.push(e.to);
}
}
}
}
return pre[t]!=-1;
}
void MCMF(int s, int t, int &cost, int &flow)
{
while(SPFA(s, t))
{
int flow_min = inf;
for(int i=pre[t]; i!=-1; i=pre[edge[i^1].to]) //找到最小流量,edge[i^1]是第i边的反向边
{
Edge e = edge[i];
flow_min = min(flow_min, e.cap-e.flow);
}
flow += flow_min;
for(int i=pre[t]; i!=-1; i=pre[edge[i^1].to]) //改变cost
{
edge[i].flow += flow_min;
edge[i^1].flow -= flow_min;
cost += edge[i].cost*flow_min;
}
}
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
int cost = 0, flow = 0;
init();
creat_graph();
int source, sink;
scanf("%d%d", &source, &sink);
MCMF(source, sink, cost, flow);
printf("最小费用是:%d\n最大费用是:%d\n", cost, flow);
}
return 0;
}