-
Notifications
You must be signed in to change notification settings - Fork 0
/
最小费用最大流
92 lines (88 loc) · 2.27 KB
/
最小费用最大流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
#include <algorithm>
#define INF (1 << 21)
#define N 15
using namespace std;
struct edge {
int from,to,cap, flow, cost;
edge(int a,int b,int c,int d,int e) {
from = a;
to = b;
cap = c;
flow = d;
cost = e;
}
};
struct solve {
int n,m;
vector<edge> edges;
vector<int>G[N];
int a[N];
int p[N];
int d[N];
int inq[N];
solve(int n,int m) {
this->n = n;
this->m = m;
}
void addEdge(int from,int to,int cap,int cost) {
edges.push_back(edge(from,to,cap,0,cost));
edges.push_back(edge(to,from,0,0,-cost));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool ford(int s,int t,int& flow,long long& cost) {
for (int i = 0 ; i < n; i++) {
d[i] = INF;
}
memset(inq,0,sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> q;
q.push(s);
while(!q.empty()) {
int u = q.front(); q.pop();
inq[u] = 0;
for (int i = 0 ; i < G[u].size(); i++) {
edge& e = edges[ G[u][i] ];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap-e.flow);
if(!inq[e.to]) {
q.push(e.to);
inq[e.to] = 1;
}
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += (long long)d[t] * (long long)a[t];
for (int u = t; u != s; u = edges[ p[u] ].from) {
edges[ p[u] ].flow += a[t];
edges[ p[u]^1 ].flow -= a[t];
}
return true;
}
int minCostMaxFlow(int s,int t,long long& cost) {
int flow = 0;
cost = 0;
while(ford(s,t,flow,cost));
return flow;
}
};
int main() {
solve s(4,5);
for(int i = 0 ; i < 5; i++) {
int x,y,c,a; cin >> x >> y >> c >> a;
s.addEdge(x,y,c,a);
}
long long cost = 0;
cout << s.minCostMaxFlow(0,3,cost) << endl;
cout << cost << endl;
return 0;
}