最短增广路算法

Dinic算法

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define INF 0x3f3f3f3f
 4 #define M(a, b) memset(a, b, sizeof(a))
 5 const int N = 1e3 + 5;
 6 struct Edge {
 7     int from, to, cap, flow;
 8 };
 9 
10 struct Dinic {
11     int n, m, s, t;
12     vector<Edge> edges;
13     vector<int> G[N];
14     bool vis[N];
15     int d[N], cur[N];
16 
17     void AddEdge(int from, int to, int cap) {
18         edges.push_back((Edge){from, to, cap, 0});
19         edges.push_back((Edge){to, from, 0, 0});
20         m = edges.size();
21         G[from].push_back(m-2); G[to].push_back(m-1);
22     }
23 
24     bool bfs() {
25         M(vis, 0);
26         queue<int> q;
27         q.push(s);
28         d[s] = 0; vis[s] = 1;
29         while (!q.empty()) {
30             int x = q.front(); q.pop();
31             for (int i = 0; i < G[x].size(); ++i) {
32                 Edge &e = edges[G[x][i]];
33                 if (!vis[e.to] && e.cap > e.flow) {
34                     vis[e.to] = 1;
35                     d[e.to] = d[x] + 1;
36                     q.push(e.to);
37                 }
38             }
39         }
40         return vis[t];
41     }
42 
43     int dfs(int x, int a) {
44         if (x == t || a == 0) return a;
45         int flow = 0, f;
46         for (int &i = cur[x]; i < G[x].size(); ++i) {
47             Edge &e = edges[G[x][i]];
48             if (d[e.to] == d[x] + 1 && (f = dfs(e.to, min(a, e.cap-e.flow))) > 0) {
49                 e.flow += f;
50                 edges[G[x][i]^1].flow -= f;
51                 flow += f; a -= f;
52                 if (a == 0) break;
53             }
54         }
55         return flow;
56     }
57 
58     int Maxflow(int s, int t) {
59         this->s = s; this->t = t;
60         int flow = 0;
61         while (bfs()) {
62             M(cur, 0);
63             flow += dfs(s, INF);
64         }
65         return flow;
66     }
67 
68 };
View Code
原文地址:https://www.cnblogs.com/robin1998/p/6724706.html