Hdu1914稳定婚姻匹配

题意:

给出 n 个男生,n 个女生,给出他们对异性的喜欢顺序,求一个稳定的婚姻组合。

思路:

稳定婚姻匹配裸题

#include <cstdio>
#include <cstring>
#include <algorithm>
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 30;
using namespace std;

int n; 
int w_love[maxn][maxn], m_love[maxn][maxn];		// 女孩,男孩的喜爱排名 
int boyfriend[maxn], girlfriend[maxn];
int man_rejected[maxn];					// 男孩i被拒绝的次数 
int rank1[maxn][maxn];					// rank1[i][j]: 男孩 j 在女孩 i 心中的的排名
					
void GaleShapley(){
	for(int i = 0; i < n; ++i){
		boyfriend[i] = -1; girlfriend[i] = -1;
		man_rejected[i] = 0;
		for(int j = 0; j < n; ++j) rank1[i][w_love[i][j]] = j; 
	}
	bool single = true;
	while(single){
		single = false;
		for(int i = 0; i < n; ++i){
			if(girlfriend[i] != -1) continue;		// 男孩已经有女友
			single = true;
			int j = man_rejected[i]++;
			int w = m_love[i][j];		// 男孩可追求的最喜欢的女孩
			int m = boyfriend[w];		// 女孩当前男友
			if(m == -1||rank1[w][i] < rank1[w][m]){	// 相比现男友,女孩更喜欢男孩 i 
				boyfriend[w] = i; girlfriend[i] = w;
				if(m != -1) girlfriend[m] = -1;		// 现男友被抛弃,变成单身 
			}
		}
	}
}

int Id[256];
char m_name[30], w_name[30];
struct Node{
	char m,w;
	bool operator < (const Node& rhs) const{
	    return m < rhs.m;
	}
}ans[30];

int main()
{
    freopen("in.txt","r",stdin);
    int T; scanf("%d",&T);
    while(T--){
    	scanf("%d",&n); getchar();
    	char ch;
    	for(int i = 0; i < n; ++i){
    		scanf("%c",&ch); getchar();
    		Id[ch] = i; m_name[i] = ch;
		}
		for(int i = 0; i < n; ++i){
    		scanf("%c",&ch); getchar();
    		Id[ch] = i; w_name[i] = ch;
		}
		char str[30];
    	for(int i = 0; i < n; ++i){
    		scanf("%s",str);
    		for(int j = 0; j < n; ++j) m_love[Id[str[0]]][j] = Id[str[j+2]];
		}
    	for(int i = 0; i < n; ++i){
    		scanf("%s",str);
    		for(int j = 0; j < n; ++j) w_love[Id[str[0]]][j] = Id[str[j+2]];
		}
    	
    	GaleShapley();
    	
    	for(int i = 0; i < n; ++i) {ans[i].m = m_name[i]; ans[i].w = w_name[girlfriend[i]];}
    	sort(ans, ans+n);
    	for(int i = 0; i < n; ++i) printf("%c %c\n",ans[i].m,ans[i].w);
    	if(T) puts("");
	}
    fclose(stdin);
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值