int n1, n2; // 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 ++ ;
}
例题:
完美牛棚
import java.util.*;
public class Main {
static int INF = 0x3f3f3f3f;
static int N = 205;
static int M = 2005;
static int n,m;
static int []match = new int [N];
static boolean []st = new boolean[N];
static int h[] = new int [N];
static int e[]= new int[M];
static int ne[] = new int[M];
static int idx;
static void add(int a,int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
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;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
Arrays.fill(h, -1);
for(int i = 1; i <= n; i ++ ) {
int cnt = sc.nextInt();
while(cnt --> 0) {
int a = sc.nextInt();
add(i,a);
}
}
int res = 0;
for(int i = 1; i <= n; i ++ ) {
Arrays.fill(st,false);
if(find(i)) res ++;
}
System.out.println(res);
sc.close();
}
}