这个算法很经典 ,不过我不会证明,可以看看百度百科,讲得很清楚,数学家们已经证明过了,我们直接用就行。
对于这个算法,总是对男性有利,在稳定婚姻的前提下,每个男性都尽可能选到自己最喜欢的女性。
而女性则不然。
这个题目是要让女性有最好的选择,直接男性当作"算法里的女性"处理,女性当作"算法里的男性"处理 就行了。
最后输出 "算法里的男性"选择结果。
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<climits>
#include<queue>
#include<vector>
#include<map>
#include<sstream>
#include<set>
#include<stack>
#include<cctype>
#include<utility>
#pragma comment(linker, "/STACK:102400000,102400000")
#define PI 3.1415926535897932384626
#define eps 1e-10
#define sqr(x) ((x)*(x))
#define FOR0(i,n) for(int i=0 ;i<(n) ;i++)
#define FOR1(i,n) for(int i=1 ;i<=(n) ;i++)
#define FORD(i,n) for(int i=(n) ;i>=0 ;i--)
#define lson num<<1,le,mid
#define rson num<<1|1,mid+1,ri
#define MID int mid=(le+ri)>>1
#define zero(x)((x>0? x:-x)<1e-15)
#define mk make_pair
#define _f first
#define _s second
using namespace std;
//const int INF= ;
typedef long long ll;
//const ll inf =1000000000000000;//1e15;
//ifstream fin("input.txt");
//ofstream fout("output.txt");
//fin.close();
//fout.close();
//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
const int INF =0x3f3f3f3f;
const int maxn=1000+10 ;
//const int maxm= ;
//by yskysker123
int pre[maxn][maxn];
int wife[maxn];
int husband[maxn];
int order[maxn][maxn];
int nex[maxn];
queue<int >q;
int n;
void engage(int man ,int woman)
{
int x=husband[woman];
if(x) wife[x]=0,q.push(x);//掉了q.push(x)!!!!!
husband[woman]=man;
wife[man]=woman;
}
void BFS()
{
while(!q.empty())
{
int man=q.front();q.pop();
int woman=pre[man][nex[man]++];//写成了int woman=nex[man]++;
if(!husband[woman]) engage(man,woman);
else if( order[woman][man]< order[woman][husband[woman]] )
engage(man,woman);
else q.push(man);
}
}
int main()
{
int T;scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
wife[i]=0;
for(int j=1;j<=n;j++)
{
scanf("%d",&pre[i][j]);
}
q.push(i);
nex[i]=1;
}
int x;
for(int i=1;i<=n;i++)
{
husband[i]=0;
for(int j=1;j<=n;j++)
{
scanf("%d",&x);
order[i][x]=j;
}
}
BFS();
for(int i=1;i<=n;i++)
{
printf("%d\n",wife[i]);
}
if(T>0) putchar('\n');
}
return 0;
}