最大流
1 struct Dinic
2 {
3 int head[maxn], tot, cur[maxn];
4 int dis[maxn];
5 int s, e;
6 queue<int>q;
7
8 struct node
9 {
10 int v, w;
11 int next;
12 }p[maxn];
13
14 void init()
15 {
16 tot = 0;
17 memset(head, -1, sizeof head);
18 }
19
20 void add(int u, int v, int w)
21 {
22 p[tot].v = v;
23 p[tot].w = w;
24 p[tot].next = head[u];
25 head[u] = tot++;
26 }
27
28 void addEdge(int u, int v, int w)
29 {
30 add(u, v, w);
31 add(v, u, 0);
32 }
33
34 bool bfs()
35 {
36 memset(dis, 0, sizeof dis);
37 while (!q.empty()) q.pop();
38 dis[s] = 1;
39 q.push(s);
40 while (!q.empty())
41 {
42 int x = q.front();
43 q.pop();
44 for (int i = head[x]; i != -1; i = p[i].next)
45 {
46 int v = p[i].v, w = p[i].w;
47 if (!dis[v] && w)
48 {
49 dis[v] = dis[x] + 1;
50 q.push(v);
51 }
52 }
53 }
54 if (dis[e]) return true;
55 return false;
56 }
57
58 int dfs(int x, int W)
59 {
60 if (x == e || W == 0) return W;
61 int res = 0;
62 for (int i = cur[x]; i != -1; i = p[i].next)
63 {
64 cur[x] = p[i].next;
65 int v = p[i].v, w = p[i].w;
66 if (dis[v] == dis[x] + 1)
67 {
68 int f = dfs(v, min(w, W));
69 p[i].w -= f;
70 p[i ^ 1].w += f;
71 W -= f;
72 res += f;
73 if (W == 0) break;
74 }
75 }
76 return res;
77 }
78
79 int getMaxFlow()
80 {
81 int ans = 0;
82 while (bfs())
83 {
84 for (int i = s; i <= e; ++i) cur[i] = head[i];
85 ans += dfs(s, inf);
86 }
87 return ans;
88 }
89 };
费用流
1 struct Min_Cost_Max_Flow 2 { 3 struct Edge 4 { 5 int from, to, cap, flow, cost; 6 }; 7 8 vector<Edge>edges; 9 vector<int>G[maxn]; 10 bool vis[maxn]; 11 int d[maxn], p[maxn], a[maxn]; 12 int n, m, s, t; 13 14 void init(int n, int s, int t) 15 { 16 this->n = n, this->s = s, this->t = t; 17 for (int i = 1; i <= n; ++i) 18 { 19 G[i].clear(); 20 } 21 edges.clear(); 22 } 23 24 void add_edge(int from, int to, int cap, int cost) 25 { 26 edges.push_back({ from,to,cap,0,cost }); 27 edges.push_back({ to,from,0,0,-cost }); 28 m = edges.size(); 29 G[from].push_back(m - 2); 30 G[to].push_back(m - 1); 31 } 32 33 bool SPFA(int& flow, int& cost) 34 { 35 memset(d, inf, sizeof d); 36 memset(vis, false, sizeof vis); 37 memset(p, -1, sizeof p); 38 d[s] = 0, vis[s] = true, p[s] = 0, a[s] = inf; 39 40 std::queue<int>que; 41 que.push(s); 42 while (!que.empty()) 43 { 44 int u = que.front(); 45 que.pop(); 46 vis[u] = false; 47 for (int i = 0; i < G[u].size(); ++i) 48 { 49 Edge& e = edges[G[u][i]]; 50 if (e.cap > e.flow&& d[e.to] > d[u] + e.cost) 51 { 52 d[e.to] = d[u] + e.cost; 53 p[e.to] = G[u][i]; 54 a[e.to] = std::min(a[u], e.cap - e.flow); 55 if (!vis[e.to]) 56 { 57 vis[e.to] = true; 58 que.push(e.to); 59 } 60 } 61 } 62 } 63 64 if (d[t] == inf) return false; 65 flow += a[t]; 66 cost += d[t] * a[t]; 67 int u = t; 68 while (u != s) 69 { 70 edges[p[u]].flow += a[t]; 71 edges[p[u] ^ 1].flow -= a[t]; 72 u = edges[p[u]].from; 73 } 74 return true; 75 } 76 77 void solve(int& flow, int& cost) 78 { 79 flow = cost = 0; 80 while (SPFA(flow, cost)); 81 } 82 };
最小费用最大流:模板
最大费用最大流:费用变负数