nyoj 239 月老的难题 (最大二分图匹配匈牙利算法)

1 篇文章 0 订阅
1 篇文章 0 订阅

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=239

月老的难题

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述

月老准备给n个女孩与n个男孩牵红线,成就一对对美好的姻缘。

现在,由于一些原因,部分男孩与女孩可能结成幸福的一家,部分可能不会结成幸福的家庭。

现在已知哪些男孩与哪些女孩如果结婚的话,可以结成幸福的家庭,月老准备促成尽可能多的幸福家庭,请你帮他找出最多可能促成的幸福家庭数量吧。

假设男孩们分别编号为1~n,女孩们也分别编号为1~n。

输入
第一行是一个整数T,表示测试数据的组数(1<=T<=400)
每组测试数据的第一行有两个整数n,K,其中男孩的人数与女孩的人数都是n。(n<=500,K<=10 000)
随后的K行,每行有两个整数i,j表示第i个男孩与第j个女孩有可能结成幸福的家庭。(1<=i,j<=n)
输出
对每组测试数据,输出最多可能促成的幸福家庭数量
样例输入
1
3 4
1 1
1 3
2 2
3 2
样例输出
2

在啊哈算法上学习了一下匈牙利算法,发现上面的代码有错误,本题的样例结果不了,改对了之后发现用邻接矩阵会超时,参考了大神的博客用邻接表写了一发过了。

参考博客:http://blog.csdn.net/u012629369/article/details/23974227    感谢!!


邻接表:

#include <iostream> 
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
int n, k;
vector<int> v[510];
int match[510];
int book[510];
int dfs(int x) {
	int i;
	for(i = 0; i < v[x].size(); i++) {
		int t = v[x][i];
		if(book[t] == 0) {
			book[t] = 1;
			if(match[t] == 0 || dfs(match[t])) {
				match[t] = x;
				return 1;
			}
		}
	}
	return 0;
}
int main() {
	int T;
	scanf("%d", &T);
	while(T--) {
		int i, j;
		scanf("%d %d", &n, &k);
		for(i = 1; i <= n; i++) {
			v[i].clear();
			match[i] = 0;
		}
		int s, e;
		for(i = 1; i <= k; i++) {
			scanf("%d %d", &s, &e);
			v[s].push_back(e);
		}
		int sum = 0;
		for(i = 1; i <= n; i++) {
			for(j = 1; j <= n; j++) book[j] = 0;
			if(dfs(i)) sum++;
		}
		printf("%d\n", sum);
	}
	return 0;
}


下面是用邻接矩阵的写法(超时):

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cctype>
using namespace std;
int n, k;
int map[1010][1010];
int book[1010];
int match[1010];
int dfs(int x) {
	int i;
	for(i = 1; i <= 2 * n; i++) {
		if(book[i] == 0 && map[x][i] == 1) {
			book[i] = 1;
			if(match[i] == 0 || dfs(match[i])) {
				match[i] = x;
				match[x] = i;
				return 1;
			}
		}
	}
	return 0;
}
int main () {
	int T;
	scanf("%d", &T);
	while(T--) {
		scanf("%d %d", &n, &k);
		int i, j;
		int x, y;
		memset(map, 0, sizeof(map));
		memset(match, 0, sizeof(match));
		for(i = 0; i < k; i++) {
			scanf("%d %d", &x, &y);
			map[x][y + n] = 1;
			map[y + n][x] = 1;
		}
		int sum = 0;
		for(i = 1; i <= n; i++) {  //只需查一半 
			for(j = 1; j <= 2 * n; j++) book[j] = 0;
			if(dfs(i)) sum++;
		}
		printf("%d\n", sum);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值