#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<cstdio>
using namespace std;
const int maxn=500+5;
int pref[maxn][maxn],order[maxn][maxn],Next[maxn];
int future_husband[maxn],future_wife[maxn];
queue<int> q;
map<string,int> Boy,Gril;
string boy[maxn],gril[maxn];
void engage(int man,int woman)
{
int m=future_husband[woman];
if(m)
{
future_wife[m]=0;
q.push(m);
}
future_husband[woman]=man;
future_wife[man]=woman;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
Boy.clear();Gril.clear();
string ss;
for(int i=1;i<=n;i++){
cin>>boy[i];
Boy[boy[i]]=i;
for(int j=1;j<=n;j++){
string g;
cin>>g;
if(i==1) {
gril[j]=g;
Gril[g]=j;
pref[i][j]=Gril[g];
}
else{
pref[i][j]=Gril[g];
}
}
Next[i]=1;
future_wife[i]=0;
q.push(i);
}
for(int i=1;i<=n;i++){
string g;
cin>>g;
int idx=Gril[g];
for(int j=1;j<=n;j++){
string b;
cin>>b;
order[idx][Boy[b]]=j;
}
future_husband[i]=0;
}
while(!q.empty())
{
int man=q.front();q.pop();
int woman=pref[man][Next[man]++];
if(future_husband[woman]==0) engage(man,woman);
else if(order[woman][man]<order[woman][future_husband[woman]]) engage(man,woman);
else q.push(man);
}
while(!q.empty()) q.pop();
for(int i=1;i<=n;i++)
{
cout<<boy[i]<<" "<<gril[future_wife[i]]<<endl;
}
}
return 0;
}
ZOJ 1576 Marriage is Stable(稳定婚姻问题)
最新推荐文章于 2019-07-25 20:51:32 发布