最小费用最大流

传送门:https://www.luogu.org/problem/P3381

反正就是求最大流+最短路但是弱得一批的我还是不会用Dijkstra做于是放的是最好看最简单的SPFA的代码

相信蒟蒻最懂你的需要

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m;
 4 struct edge{
 5     int to,nxt,flow,dis;
 6 }e[100010];int tot=-1;
 7 int first[100010];
 8 int dis[100010],flow[100010];
 9 bool vis[100010];
10 int pre[100010],last[100010];
11 int s,t;
12 int maxflow,mincost;
13 inline void add_edge(int a,int b,int c,int d)
14 {
15     e[++tot].to=b;
16     e[tot].flow=c;
17     e[tot].nxt=first[a];
18     e[tot].dis=d;
19     first[a]=tot;
20 }
21 inline int kd()
22 {
23     int x=0,f=1;char ch=getchar();
24     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
25     while(ch>='0'&&ch<='9'){x=x*10+(ch^48);ch=getchar();}
26     return x*f;
27 }
28 bool spfa()
29 {
30     memset(dis,0x3f3f3f3f,sizeof(dis));
31     memset(vis,false,sizeof(vis));
32     memset(flow,0x3f3f3f3f,sizeof(flow));
33     queue<int>q;
34     q.push(s);
35     vis[s]=true;
36     dis[s]=0;
37     pre[t]=-1;
38     while(q.empty()==false)
39     {
40         int now=q.front();
41         q.pop();
42         vis[now]=false;
43         for(register int i=first[now];i!=-1;i=e[i].nxt)
44         {
45             if(e[i].flow!=0&&dis[e[i].to]>dis[now]+e[i].dis)
46             {
47                 dis[e[i].to]=dis[now]+e[i].dis;
48                 pre[e[i].to]=now;
49                 last[e[i].to]=i;
50                 flow[e[i].to]=min(flow[now],e[i].flow);
51                 if(vis[e[i].to]==false)
52                 {
53                     vis[e[i].to]=true;
54                     q.push(e[i].to);
55                 }
56             }
57         }
58     }
59     if(pre[t]==-1)return false;
60     return true;
61 }
62 void mcmf()
63 {
64     while(spfa())
65     {
66         int now=t;
67         maxflow+=flow[t];
68         mincost+=dis[t]*flow[t];
69         while(now!=s)
70         {
71             e[last[now]].flow-=flow[t];
72             e[last[now]^1].flow+=flow[t];
73             now=pre[now];
74             
75         }
76     }
77 }
78 int main()
79 {
80     memset(first,-1,sizeof(first));
81     n=kd(),m=kd(),s=kd(),t=kd();
82     for(register int i=1;i<=m;i++)
83     {
84         int a=kd(),b=kd(),c=kd(),d=kd();
85         add_edge(a,b,c,d);
86         add_edge(b,a,0,-d);
87     }
88     mcmf();
89     cout<<maxflow<<" "<<mincost<<endl;
90     return 0;
91 }
原文地址:https://www.cnblogs.com/1129-tangqiyuan/p/11751495.html