最小费用最大流模板

来源:互联网 发布:手机画板软件免费版 编辑:程序博客网 时间:2024/06/09 16:37
#include<bits/stdc++.h>using namespace std;#define INF 0x3f3f3f3ftypedef long long LL;const int M=2010;//边数注意啦,我们这东西是有逆向边的,所以边数要×2哦const int N=510;//点数struct edge{    int to;    int next;    int cap;    int cost;} e[11000];int head[N],tot;int d[N], pre[N], path[N];//pre是用来记录路径的,表示这个点的上一个点是谁,path是用来记录路径所对应的边数bool vis[N];void init(){    memset(head,-1,sizeof(head));    tot = 0;}void addedge(int s, int t, int cap, int cost){    e[tot].to=t;    e[tot].cap=cap;    e[tot].cost=cost;    e[tot].next=head[s];    head[s] = tot++;    e[tot].to=s;    e[tot].cap=0;    e[tot].cost=-cost;    e[tot].next=head[t];    head[t] = tot++;}int spfa(int s, int t){    memset(d,INF,sizeof(d));    memset(pre,-1,sizeof(pre));    memset(path,-1,sizeof(path));    memset(vis,false,sizeof(vis));    d[s] = 0;    vis[s] = true;    queue<int>q;    q.push(s);    while (!q.empty())    {        int u = q.front();        q.pop();        vis[u] = false;        for (int i = head[u]; i!=-1; i = e[i].next)        {            int v = e[i].to;            if (d[v] > d[u] + e[i].cost && e[i].cap > 0)            {                d[v] = d[u] + e[i].cost;                pre[v] = u;                path[v] = i;                if (!vis[v])                {                    vis[v] = true;                    q.push(v);                }            }        }    }    return d[t] != INF;}int MinCostMaxFlow(int s, int t,int &cost){    int flow;    flow=cost=0;    while (spfa(s, t))//找增广路直到找不到为止    {        int minn = INF;        for (int i = t; i != s && ~i; i = pre[i])            minn = min(minn, e[path[i]].cap);        for (int i = t; i != s && ~i; i = pre[i])        {            e[path[i]].cap -= minn;            e[path[i] ^ 1].cap += minn;        }        flow += minn;        cost += minn * d[t];    }    return flow;}int main(){    int n,m;    while(~scanf("%d %d",&n,&m))    {        init();        for (int k=1;k<=n;k++)        {            int a,b,c,d;            scanf("%d %d %d %d",&a,&b,&c,&d);            addedge(0,k,b,a);            addedge(k,n+1,d,-c);        }        for (int k=1;k<=m;k++)        {            int st,en,dis;            scanf("%d %d %d",&st,&en,&dis);            addedge(st,en,INF,dis);            addedge(en,st,INF,dis);        }        int cost(0);        MinCostMaxFlow(0,n+1,cost);        printf("%d\n",-cost);    }}


这个的思路也是找增广路,但是有所不同,我每次找的增广路都是单位费用最小的增广路,这样我们找到最大流之后,找到的就是最小费用最大流

其实这个可以干很多事情,也可以求最小费用可行流,这个在求的时候,找到的流量够了退出循环即可。

那如何求最小费用的增广路呢?

我们使用的是spfa(可能有负边嘛)

把cost当成路径长度就好啦

d【i】就表示从起点到i一个单位的流要的花费


原创粉丝点击