匈牙利算法

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值