- 时间复杂度是 O(nm),实际情况远小于O(nm), n表示点数,m表示边数
- 匈牙利算法主要用来求二分图的最大匹配

模板
int n1, n2;
int h[N], e[M], ne[M], idx;
int match[N];
bool st[N];
bool find(int x)
{
for (int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
st[j] = true;
if (match[j] == 0 || find(match[j]))
{
match[j] = x;
return true;
}
}
}
return false;
}
int res = 0;
for (int i = 1; i <= n1; i ++ )
{
memset(st, false, sizeof st);
if (find(i)) res ++ ;
}
public static int[] h = new int[N];
public static int[] e = new int[M];
public static int[] ne = new int[M];
public static int[] match = new int[N];
public static boolean[] st = new int[N];
public static int n1, n2;
int res = 0;
for (int i = 1; i <= n1; i++) {
Arrays.fill(st, false);
if (find(i)) {
res++;
}
}
public boolean find(int x) {
for (int i = h[x]; i != -1; i = ne[i]) {
int j = e[i];
if (!st[j]) {
st[j] = true;
if (match[j] == 0 || find(match[j])) {
match[j] = x;
return true;
}
}
}
return false;
}
练习
01 二分图的最大匹配

import java.io.*;
import java.util.*;
public class Main {
public static final int N = 510;
public static final int M = 100010;
public static int[] h = new int[N];
public static int[] e = new int[M];
public static int[] ne = new int[M];
public static boolean[] st = new boolean[N];
public static int[] match = new int[N];
public static int n1, n2, m, idx;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
String[] str1 = br.readLine().split(" ");
n1 = Integer.parseInt(str1[0]);
n2 = Integer.parseInt(str1[1]);
m = Integer.parseInt(str1[2]);
Arrays.fill(h, -1);
idx = 0;
while (m-- > 0) {
String[] str2 = br.readLine().split(" ");
int u = Integer.parseInt(str2[0]);
int v = Integer.parseInt(str2[1]);
add(u, v);
}
int res = 0;
for (int i = 1; i <= n1; i++) {
Arrays.fill(st, false);
if (find(i)) {
res++;
}
}
pw.println(res);
br.close();
pw.close();
}
public static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
public static boolean find(int x) {
for (int i = h[x]; i != -1; i = ne[i]) {
int j = e[i];
if (!st[j]) {
st[j] = true;
if (match[j] == 0 || find(match[j])) {
match[j] = x;
return true;
}
}
}
return false;
}
}