【HDOJ】1914 The Stable Marriage Problem

时间:2023-04-05 23:01:49
【HDOJ】1914 The Stable Marriage Problem

稳定婚姻问题,Gale-Shapley算法可解。

 /* 1914 */
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int maxn = ;
char s[];
char wname[];
int pref[maxn][maxn];
int order[maxn][maxn];
int nxt[maxn];
int future_husband[maxn];
int future_wife[maxn];
queue<int> Q;
int n;
int ID[]; void engage(int man, int woman) {
int m = future_husband[woman]; if (m) {
future_wife[m] = ;
Q.push(m);
} future_husband[woman] = man;
future_wife[man] = woman;
} void solve() {
while (!Q.empty()) {
int man = Q.front();
Q.pop();
int woman = pref[man][nxt[man]++];
if (!future_husband[woman]) {
engage(man, woman);
} else if (order[woman][man] < order[woman][future_husband[woman]]) {
engage(man, woman);
} else {
Q.push(man);
}
} rep(i, 'a', 'z'+) {
if (!ID[i])
continue;
printf("%c %c\n", i, wname[future_wife[ID[i]]]);
}
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif int t;
int nlc, nuc; scanf("%d", &t);
while (t--) {
scanf("%d", &n);
memset(ID, , sizeof(ID));
nlc = nuc = ;
rep(i, , n+n) {
scanf("%s", s);
if (islower(s[])) {
ID[s[]] = ++nlc;
} else {
ID[s[]] = ++nuc;
wname[nuc] = s[];
}
} while (!Q.empty())
Q.pop(); int lid, uid; rep(i, , n) {
scanf("%s", s);
lid = ID[s[]];
rep(j, , n+) {
uid = ID[s[+j]];
pref[lid][j] = uid;
}
nxt[lid] = ;
future_wife[lid] = ;
Q.push(lid);
} rep(i, , n) {
scanf("%s", s);
uid = ID[s[]];
rep(j, , n+) {
lid = ID[s[+j]];
order[uid][lid] = j;
}
future_husband[uid] = ;
}
solve();
if (t)
putchar('\n');
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}