1. 程式人生 > >The Stable Marriage Problem

The Stable Marriage Problem

turn span flag mar class color rri i++ 基本

和上一題基本一樣的

#include <iostream>
#include <cstring>
#include <map>
#define MAXN 30
using namespace std;
int mm[MAXN][MAXN], gg[MAXN][MAXN], p[MAXN];
int gg_match[MAXN], mm_match[MAXN];
char idx[2*MAXN];
map<char, int> mp;
int main() {
    int t, n;
    cin >> t;
    while
(t--) { cin >> n; char ch; int cnt = 0; mp.clear(); for (int i = 0; i < 2 * n; i++) cin >> ch; for (int i = 1; i <= n; i++) { cin >> idx[i] >> ch; mp[idx[i]] = i; for (int j = 1; j <= n; j++) { cin
>> ch; if (mp[ch] == 0) { mp[ch] = ++cnt; idx[cnt+n] = ch; } gg[i][j] = mp[ch]; } } for (int i = 1; i <= n; i++) { char gir; cin >> gir >> ch;
int a = mp[gir]; for (int j = 1; j <= n; j++) { cin >> ch; int b = mp[ch]; mm[a][b] = j; } } bool flag = true; for (int i = 1; i <= n; i++) p[i] = 1; memset(mm_match, -1, sizeof(mm_match)); memset(gg_match, -1, sizeof(gg_match)); while (flag) { flag = false; for (int i = 1; i <= n; i++) { if (gg_match[i] == -1 && p[i] <= n) { int a = gg[i][p[i]++]; if (mm_match[a] == -1) mm_match[a] = i, gg_match[i] = a; else if (mm[a][i] < mm[a][mm_match[a]]) { gg_match[i] = a; gg_match[mm_match[a]] = -1; mm_match[a] = i; } flag = true; } } } for (int i = 0; i < 26; i++) { for (int j = 1; j <= n; j++) if (idx[j] == a + i) { cout << idx[j] << << idx[gg_match[j]+n] << endl; break; } } if (t) cout << endl; } return 0; }

The Stable Marriage Problem