# 網絡流_加上了當前弧優化的Dinic算法

5 3 4
5
4 3
2 2
5 2
5 1
5 3
5
1 3
3 1
2 2
3 3
4 3

2

M1=5，表示書和練習冊共有5個可能的對應關係，分別爲：書4和練習冊3、書2和練習冊2、書5和練習冊2、書5和練習冊1以及書5和練習冊3。

M2=5，表示數和答案共有5個可能的對應關係，分別爲：書1和答案3、書3和答案1、書2和答案2、書3和答案3以及書4和答案3。

AC代碼：

``````#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int N = 4e4 + 5, M = 2e5;
const int inf = 0x3f3f3f3f;

int n1, n2, n3, m1, m2, s, t, maxflow;
int h[N], w[M], e[M], ne[M], idx;
int d[N];
int now[M];

inline void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, w[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}

inline bool bfs(void) {
queue<int> q;
while(q.size()) q.pop();
memset(d, 0, sizeof d);

d[s] = 1, q.push(s);

while(q.size()) {
int u = q.front(); q.pop();

for(int i = h[u]; i != -1; i = ne[i]) {
int v = e[i];
if(w[i] && !d[v]) {
d[v] = d[u] + 1;
q.push(v);
}
}
}

return d[t] != 0;
}

inline int dinic(int u, int flow) {
int i;

if(u == t) return flow;

for(i = now[u]; i != -1; i = ne[i]) {
int v = e[i];
if(w[i] && d[v] == d[u] + 1) {
int k = dinic(v, min(flow, w[i]));
if(k) {
w[i] -= k;
w[i ^ 1] += k;

return k;
} else d[v] = 0;
}
now[u] = i;
}

return 0;
}

int main(void) {
//	freopen("in.txt", "r", stdin);

scanf("%d%d%d", &n1, &n2, &n3);
memset(h, -1, sizeof h);
s = n2 + 2 * n1 + n3 + 1, t = s + 1;

//源點連練習冊
for(int i = 1; i <= n2; i ++)

//練習冊連書
scanf("%d", &m1);
for(int i = 1; i <= m1; i ++) {
int a, b;
scanf("%d%d", &a, &b);
}

//書連書
for(int i = 1; i <= n1; i ++)
add(n2 + i, n2 + n1 + i, 1);

//書連答案
scanf("%d", &m2);
for(int i = 1; i <= m2; i ++) {
int a, b;
scanf("%d%d", &a, &b);
add(n2 + n1 + a, n2 + 2 * n1 + b, 1);
}

//答案連匯點
for(int i = 1; i <= n3; i ++)
add(n2 + 2 * n1 + i, t, 1);

int flow;
while(bfs()) {
memcpy(now, h, sizeof h);
while(flow = dinic(s, inf)) maxflow += flow;
}

printf("%d\n", maxflow);

//	fclose(stdin);
return 0;
}
``````