具体参见上篇博客。
都是类似的问题,不过我发现这类问题好像输入格式的控制会稍微难一点。
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;
}