题目
给定一个二分图,其中左半部包含n1个点(编号1n1),右半部包含n2个点(编号1n2),二分图共包含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.util.*;
class Main{
static int N=510;
static int M=100010;
static int index=0;
static int n1;
static int[] h=new int[N];
static int[] e=new int[M];
static int[] ne=new int[M];
static boolean[] st=new boolean[N];
static int[] match=new int[N];
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
n1=sc.nextInt();
int n2=sc.nextInt();
int m=sc.nextInt();
while(m-->0){
int u=sc.nextInt();
int v=sc.nextInt();
add(u,v);
}
int count=0;
for(int i=1;i<=n1;i++){
Arrays.fill(st,false);
if(find(i)) count++;
}
System.out.print(count);
}
public static void add(int a,int b){
e[++index]=b;
ne[index]=h[a];
h[a]=index;
}
public static boolean find(int x){
for(int i=h[x];i!=0;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;
}
}
算法解析
这个算法可以说是最好理解的算法,就是男女配对的算法.
算法的核心在于对每个男生匹配的函数find().
每个男生在找女生的时候都有一个原则,就是不会选别人预定的女生;//这是大前提
然后依次在自己的目标女生中寻找(有被预定的女生就跳过)
找到后将其预定(后面的就不能选了) (不管这个女生有没有couple)
- 如果这个女生有couple,就问这个女生的couple能否在当前女生被预定的前提下找到其他人 可以找到 就返回true
- 如果没有couple,那我就是他的couple,返回true
都遍历完了都没有成功的就返回false