洛谷 P3381 【模板】最小费用最大流

题目链接:https://www.luogu.org/problemnew/show/P3381
解题思路:最小费用最大流模板
就是spfa版的dinic
代码

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node
{
    int next,len,w,to;
} edge[100010];

int head[5050],cnt,dis[100010],flow[100010],vis[100010],pre[100010],last[100010];
int maxflow,mincost;

void addedge(int u,int v,int len,int w)
{
    edge[cnt].to=v;
    edge[cnt].len=len;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}

bool spfa(int s,int t)
{
    memset(dis,0x7f,sizeof(dis));
    memset(flow,0x7f,sizeof(flow));
    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=edge[i].next)
        {
            if(edge[i].len>0&&dis[edge[i].to]>dis[now]+edge[i].w)
            {
                dis[edge[i].to]=dis[now]+edge[i].w;
                pre[edge[i].to]=now;
                last[edge[i].to]=i;
                flow[edge[i].to]=min(flow[now],edge[i].len);
                if(!vis[edge[i].to])
                {
                    vis[edge[i].to]=1;
                    q.push(edge[i].to);
                }
            }
        }
    }
    return pre[t]!=-1;
}

void mcmf(int s,int t)
{
    while(spfa(s,t))
    {
        int now=t;
        maxflow+=flow[t];
        mincost+=flow[t]*dis[t];
        while(now!=s)
        {
            edge[last[now]].len-=flow[t];
            edge[last[now]^1].len+=flow[t];
            now=pre[now];
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    int n,m,s,t;
    cin>>n>>m>>s>>t;
    memset(head,-1,sizeof(head));
    int u,v,w,tt;
    cnt=0;
    for(int i=0; i<m; i++)
    {
        cin>>u>>v>>w>>tt;
        addedge(u,v,w,tt);
        addedge(v,u,0,-tt);
    }
    mcmf(s,t);
    cout<<maxflow<<" "<<mincost<<endl;
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注