图论——网络流——最小费用流(1.0版)

一、spfa+EK算法:

算法思路:
1、通过spfa找增广路
{
将费用看成 距离,通过在最小距离的前提下找增广路。
}
2、通过EK计算增加量

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn = 5000 + 7;
/**********邻接表数组形式***********/
struct Edge{/***表边**/
   int from,to;/****起点终点***/
   int next;/*****相同起点 的下一条边***/
   int cap,flow;/*****该边 的 容量 和流量***/
   int cost;/****花费**/
}edge[maxn*20];
int head[maxn];/****表头***/
int pre[maxn];
int dist[maxn],n,m,tot,s,t;
bool vis[maxn];

/***加边函数********/
void addEdge(int a,int b,int c,int cost){//注意反向弧的负权值
     edge[tot].from = a;edge[tot].to = b;/*****a到 b****/
     edge[tot].next = head[a];/*****他的下一条边 是 之前最后一条 以 a为起点的边******/
     edge[tot].cap = c;edge[tot].flow = 0;/*******容量 流量 流量初始化 为 0*******/
     edge[tot].cost = cost;head[a] = tot++;/***他成为 目前 以a 为起点的最后一条边****/

     /*****反向边的建立 反向边的容量 初始化为 0******/
     edge[tot].from = b;edge[tot].to = a;edge[tot].next = head[b];edge[tot].cap = 0;edge[tot].flow = 0;edge[tot].cost = -cost;head[b] = tot++;
}
bool SPFA(){//SPFA求增广路,dist[t]保存最小花费  ,
    memset(dist,INF,sizeof(dist));
    memset(vis,0,sizeof(vis));
    queue<int> que;
    dist[s] = 0;
    vis[s] = 1;
    que.push(s);
    while(!que.empty()){
        int u = que.front();
        que.pop();
        vis[u] = 0;
        for(int i = head[u];i!= -1/**可以 用~i*/;i = edge[i].next){
            int v = edge[i].to;
            if(edge[i].cap > edge[i].flow && dist[v] > dist[u] + edge[i].cost){
                dist[v] = dist[u] + edge[i].cost;
                pre[v] = i;
                if(!vis[v]){
                    vis[v] = 1;
                    que.push(v);
                }
            }
        }
    }
    if(dist[t]!=INF)return true;
    return false;
}

int CostFlow(int &flow){//EK算法
    int mincost = 0;
    while(SPFA()){//能找到增广路
        int Min = INF;
        for(int i = t;i!=s;i = edge[pre[i]].from)
        {//寻找最小流
            Min = min(Min,edge[pre[i]].cap - edge[pre[i]].flow);
        }
        for(int i = t;i!=s;i = edge[pre[i]].from){//处理所有边
            edge[pre[i]].flow+=Min;
            edge[pre[i]^1].flow-=Min;
        }
        flow+=Min;
        mincost+=(dist[t]*Min);//累和最小花费
    }
    return mincost;
}
int main()
{
    
    int T;
    scanf("%d",&T);
    while(T--){
        tot = 0;
        memset(head,-1,sizeof(head));
        scanf("%d%d%d%d",&n,&m,&s,&t);
        for(int i = 0;i<m;i++){
            int a,b,c,cost;
            scanf("%d%d%d%d",&a,&b,&c,&cost);
            addEdge(a,b,c,cost);
        }
        int MaxFlow = 0;
        int MinCost = CostFlow(MaxFlow);
        printf("%d %d\n",MaxFlow,MinCost);
    }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值