题意:
给出 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;
}