1. 程式人生 > >最小費用最大流spfa

最小費用最大流spfa

AI mem clas ++ int void include ons add

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 100100, INF = 0x7fffffff;
int head[maxn], d[maxn], vis[maxn], p[maxn], f[maxn];
int n, m, s, t;
int flow, value;
struct node{
    
int u, v, c, f, w, next; }Node[maxn]; void add(int u, int v, int c, int f, int w, int i) { Node[i].u = u; Node[i].v = v; Node[i].c = c; Node[i].f = f; Node[i].w = w; Node[i].next = head[u]; head[u] = i; } int spfa() { queue<int> Q; mem(vis,0); mem(p,-1);
for(int i=0; i<=n; i++) d[i] = INF; d[s] = 0; Q.push(s); vis[s] = 1; p[s] = 0; f[s] = INF; while(!Q.empty()) { int u = Q.front(); Q.pop(); vis[u] = 0; for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(d[e.v] > d[u] + e.w && e.c > e.f) { d[e.v]
= d[u] + e.w; p[e.v] = i; f[e.v] = min(f[u], e.c - e.f); if(!vis[e.v]) { Q.push(e.v); vis[e.v] = 1; } } } } if(p[t] == -1) return 0; flow += f[t]; value += f[t] * d[t]; for(int i=t; i!=s; i=Node[p[i]].u) { Node[p[i]].f += f[t]; Node[p[i]^1].f -= f[t]; } return 1; } void max_flow() { while(spfa()); printf("%d %d\n",flow,value); } int main() { mem(head,-1); cin>> n >> m >> s >> t; int cnt = 0; flow = 0, value = 0; for(int i=0; i<m; i++) { int u, v, c, w; cin>> u >> v >> c >> w; add(u,v,c,0,w,cnt++); add(v,u,0,0,-w,cnt++); } max_flow(); return 0; }

最小費用最大流spfa