【稳定婚姻问题】poj3487 The Stable Marriage Problem

具体参见上篇博客。

都是类似的问题,不过我发现这类问题好像输入格式的控制会稍微难一点。

Gale-shapley的实现会相对简单很多。其中求loc部分其实也可以用map优化一下,否则我的实现是可能退化到O(n^3)的。

当然这问题规模实在是太小了,所以也就不需要优化。。。

#include <cstdio>
#include <cstring>
#include <vector>
#include <utility>
#include <set>
#include <map>
#include <algorithm>
using namespace std;

const int MAX = 30;
int ggid[MAX], mmid[MAX];
vector<int> gg[MAX], mm[MAX];
char gglist[MAX], mmlist[MAX];
bool vis[MAX];
bool rej[MAX][MAX];
int match[MAX];
int n;

int loc(int a, int b) {
	for (int i = 0; i < n; ++i) {
		if (mm[a][i] == b) return i;
	}
}

void solve() {
	memset(vis, false, sizeof(vis));
	memset(match, -1, sizeof(match));
	memset(rej, false, sizeof(rej));
	
	bool flag = true;
	while (flag) {
		flag = false;
		for (int i = 1; i <= n; ++i) {
			if (!vis[i]) {
				for (int j = 0; j < n; ++j) {
					int &e = gg[i][j];
					if (match[e] == -1) {
						vis[i] = true;
						match[e] = i;
						//printf("1: %c match %c\n", gglist[i], mmlist[e]);
						break;
					} else if (!rej[e][i] && loc(e, match[e]) > loc(e, i)) {
						vis[match[e]] = false;
						vis[i] = true;
						match[e] = i;
						//printf("2: %c match %c\n", gglist[i], mmlist[e]);
						break;
					} else {
						rej[e][i] = true;
					}
				}
				flag = true;	
			}
		}
	}
	
	set<pair<char, char> > ans;
	for (int i = 1; i <= n; ++i) {
		ans.insert(make_pair(gglist[match[i]], mmlist[i]));
	}
	for (set<pair<char, char> >::iterator it = ans.begin(); it != ans.end(); ++it) {
		printf("%c %c\n", it->first, it->second);
	}
}

int main() {
	int T;
	scanf(" %d", &T);
	while (T--) {
		scanf(" %d", &n);
		//init
		for (int i = 0; i < MAX; ++i) {
			gg[i].clear();
			mm[i].clear();
		}
		/*
			gglist[ggid[name-'a'+1]] = name
			ggid[name-'a'+1] to get id
			gglist[id] to get name
			(the same as mm's..)
		*/
		for (int i = 1; i <= n; ++i) {
			scanf(" %c", gglist + i);
			ggid[gglist[i] - 'a' + 1]  = i;
		}
		for (int i = 1; i <= n; ++i) {
			scanf(" %c", mmlist + i);
			mmid[mmlist[i] - 'A' + 1] = i;
		}
		for (int i = 1; i <= n; ++i) {
			char ch;
			scanf(" %c%*c", &ch);
			for (int j = 1; j <= n; ++j) {
				gg[ch-'a'+1].push_back(getchar()-'A'+1);
			}
		}
		for (int i = 1; i <= n; ++i) {
			char ch;
			scanf(" %c%*c", &ch);
			for (int j = 1; j <= n; ++j) {
				mm[ch-'A'+1].push_back(getchar()-'a'+1);
			}
		}
		solve();
		if (T) putchar('\n');
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值