二分图的最大匹配,也可以称为匈牙利算法,或者找女友算法
算法描述:
- 我们认为所有妹子都是可以去尝试的
- 如果发现妹子已经有了男朋友,那么我们出于不达目的不罢休的态度,我们去找她男朋友,问他能不能换一个女朋友
- 如果他有备胎,换了女朋友,那么我们就把妹子拿下
- 如果他也没办法,换不了,那么我们也就没办法了,尽力了
题目描述:
给定一个二分图,其中左半部包含 n1 个点(编号 1∼n1),右半部包含 n2 个点(编号 1∼n2),二分图共包含 m 条边。
数据保证任意一条边的两个端点都不可能在同一部分中。
请你求出二分图的最大匹配数。
二分图的匹配:给定一个二分图 G,在 G 的一个子图 M 中,M 的边集 {E} 中的任意两条边都不依附于同一个顶点,则称 M 是一个匹配。
二分图的最大匹配:所有匹配中包含边数最多的一组匹配被称为二分图的最大匹配,其边数即为最大匹配数。
输入格式
第一行包含三个整数 n1、 n2 和 m。
接下来 m 行,每行包含两个整数 u 和 v,表示左半部点集中的点 u 和右半部点集中的点 v 之间存在一条边。
输出格式
输出一个整数,表示二分图的最大匹配数。
数据范围
1≤n1,n2≤500,
1≤u≤n1,
1≤v≤n2,
1≤m≤105
输入样例:
2 2 4
1 1
1 2
2 1
2 2
输出样例:
2
代码实现:
import java.io.*;
import java.util.*;
public class Main{
public static int[] e = new int[100010];
public static int[] ne = new int[100010];
public static int[] h = new int[510];
public static int[] match = new int[510];
public static boolean[] st = new boolean[510];
public static int idx = 0;
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] lens = br.readLine().split(" ");
int n1 = Integer.parseInt(lens[0]);
int n2 = Integer.parseInt(lens[1]);
int m = Integer.parseInt(lens[2]);
Arrays.fill(h, -1);
while (m-- > 0){
String[] res = br.readLine().split(" ");
int a = Integer.parseInt(res[0]);
int b = Integer.parseInt(res[1]);
add(a, b);
}
int res = 0;
for (int i = 1; i <= n1; i++){
Arrays.fill(st, false); //对每个男生来说,一开始所有的妹子都是没有尝试的,所以我们一定要去尝试!
if (find(i)) res++;
}
System.out.print(res);
}
public static boolean find(int t){
for (int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if (!st[j]){
st[j] = true; // 代表已经尝试过了,不后悔了
if (match[j] == 0 || find(match[j])){ // match指妹子的男朋友,0表示没有男朋友
match[j] = t;
return true;
}
}
}
return false;
}
public static void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}
学习了代码,也了解了人生智慧,共勉!