这个ISAP模板只能增广一次,在残量网络上跑就会有问题,但是效率不错。
1 namespace ISAP { 2 int tot, n, m, src, tar, qh, qt, cnt; 3 ll ans; 4 struct edge { 5 int vet, next, len; 6 } E[LEN * 2]; 7 int dis[LEN], gap[LEN], head[LEN], cur[LEN], q[LEN], vis[LEN]; 8 void add(int u, int v, int c) { 9 E[++tot] = (edge){v, head[u], c}; 10 head[u] = tot; 11 } 12 void join(int u, int v, int c) { 13 add(u, v, c); 14 add(v, u, 0); 15 } 16 void bfs(int s) { 17 qh = qt = 0; 18 q[++qt] = s; 19 dis[s] = 0; 20 vis[s] = 1; 21 while (qh < qt) { 22 int u = q[++qh]; 23 gap[dis[u]]++; 24 for (int e = head[u]; e != -1; e = E[e].next) { 25 int v = E[e].vet; 26 if (E[e ^ 1].len && !vis[v]) { 27 dis[v] = dis[u] + 1; 28 vis[v] = 1; 29 q[++qt] = v; 30 } 31 } 32 } 33 } 34 int isap(int u, int aug) { 35 if (u == tar) return aug; 36 int flow = 0; 37 for (int e = head[u]; e != -1; e = E[e].next) { 38 int v = E[e].vet; 39 if (E[e].len && dis[v] == dis[u] - 1) { 40 int tmp = isap(v, min(aug - flow, E[e].len)); 41 E[e].len -= tmp; 42 E[e ^ 1].len += tmp; 43 flow += tmp; 44 head[u] = e; 45 if (flow == aug || dis[src] == cnt) return flow; 46 } 47 } 48 if (!--gap[dis[u]++]) dis[src] = cnt; 49 ++gap[dis[u]]; 50 head[u] = cur[u]; 51 return flow; 52 } 53 ll maxflow(int s, int t) { 54 ll res = 0; 55 src = s, tar = t; 56 for (int i = 1; i <= cnt; i++) cur[i] = head[i]; 57 bfs(tar); 58 while (dis[src] < cnt) res += isap(src, oo); 59 return res; 60 } 61 void init() { 62 tot = -1, gap[0] = 0; 63 for (int i = 1; i <= cnt; i++) { 64 vis[i] = gap[i] = dis[i] = 0; 65 head[i] = -1; 66 } 67 } 68 }
这个DINIC模板可以在残量网络上增广多次。
1 namespace DINIC { 2 int tot, src, tar, n, m, qh, qt, cnt; 3 int head[LEN], cur[LEN], dis[LEN], q[LEN]; 4 struct edge { 5 int vet, next, len; 6 } E[LEN * 2]; 7 void add(int u, int v, int c) { 8 E[++tot] = (edge){v, head[u], c}; 9 head[u] = tot; 10 } 11 void join(int u, int v, int c) { 12 add(u, v, c); 13 add(v, u, 0); 14 } 15 void init() { 16 tot = -1; 17 for (int i = 1; i <= cnt; i++) head[i] = -1; 18 } 19 bool bfs() { 20 for (int i = 1; i <= cnt; i++) dis[i] = 0; 21 qh = qt = 0; 22 q[++qt] = src; 23 dis[src] = 1; 24 while (qh < qt) { 25 int u = q[++qh]; 26 for (int e = head[u]; e != -1; e = E[e].next) { 27 int v = E[e].vet; 28 if (E[e].len && !dis[v]) { 29 dis[v] = dis[u] + 1; 30 if (v == tar) return 1; 31 q[++qt] = v; 32 } 33 } 34 } 35 return dis[tar]; 36 } 37 int dfs(int u, int aug) { 38 if (u == tar || !aug) return aug; 39 int tmp = 0; 40 for (int &e = cur[u]; e != -1; e = E[e].next) { 41 int v = E[e].vet; 42 if (dis[v] == dis[u] + 1) { 43 if (tmp = dfs(v, min(aug, E[e].len))) { 44 E[e].len -= tmp; 45 E[e ^ 1].len += tmp; 46 return tmp; 47 } 48 } 49 } 50 return 0; 51 } 52 ll maxflow(int s, int t) { 53 src = s, tar = t; 54 ll res = 0; 55 int flow = 0; 56 while (bfs()) { 57 for (int i = 1; i <= cnt; i++) cur[i] = head[i]; 58 while (flow = dfs(src, oo)) res += flow; 59 } 60 return res; 61 } 62 }