AcWing 861. 二分图的最大匹配-java-关键处注释
原题链接
简单
作者:
Astarion
,
2021-02-17 22:49:43
,
所有人可见
,
阅读 297
import java.io.*;
import java.util.Arrays;
class Main {
static int n1, n2, m;
//邻接表形式存放左边到右边的边
static int idx;
static int[] h = new int[510];
static int[] e = new int[100010];
static int[] ne = new int[100010];
static {
Arrays.fill(h,-1);
}
//记录当前遍历的左边点对应的右边点是否已搜索过
static boolean[] flag = new boolean[510];
//记录右边点匹配的左边点
static int[] match = new int[510];
static void insert(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
static boolean find(int left) {
for (int i = h[left]; i != -1; i = ne[i]) {
int right = e[i];
//没搜过,进入搜索,标记为已搜索避免递归中重复搜到导致死循环
if (!flag[right]) {
flag[right] = true;
if (match[right] == 0 || find(match[right])) {
match[right] = left;
return true;
}
}
}
return false;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n1 = Integer.parseInt(strs[0]);
n2 = Integer.parseInt(strs[1]);
m = Integer.parseInt(strs[2]);
for (int i = 1; i<=m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
insert(a,b);
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
int res = 0;
for (int i = 1; i<=n1; i++) {
//关键:对于每个左边点,遍历所有相关的右边点前,先将flag数组清空
Arrays.fill(flag, false);
if (find(i)) res++;
}
out.write(String.valueOf(res));
out.flush();
out.close();
osw.close();
}
}