题意:N个女生,N个男生,女生对每个男生的好感程度不同,男生对每个女生的好感程度也不同,现在要男女生搭配跳舞,求配对方法,使得每个人都有舞伴,且不存在男A与女B是舞伴,男C与女D是舞伴,但(比起女B)男A更喜欢女D且(比起男C)女D更喜欢男A。配对完后,女生较男生更(或者同等)“幸福”(1 <= N <= 1000)。
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3037
——>>接触的第一道稳定婚姻题目,看了求婚-拒绝算法后,想A这道题,一看LA和Uva的提交情况,全Submission error,交不了,在vjudge搜了一下,发现zoj有加这题,好~题目说先输入女生对男生的排位,而RJ的《训练指南》却先输入男人对女人的排位,我想是不是搞反了?最后发现,样例也得先输入男人才通得过,这是???再看题目, we want to produce the best possible choice for the girls,女生得到自己能得到的最好的男生舞伴。终于明白了,这里的女生相当于稳定婚姻中的男人(所有男士娶到自己有可能娶到的最好的妻子,女士只能嫁给自己有可能嫁到的最差的丈夫)。
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 1000 + 10;
int N, order[maxn][maxn], pref[maxn][maxn], future_husband[maxn], future_wife[maxn], nxt[maxn];
queue<int> qu;
void engage(int man, int woman){
if(future_husband[woman]) qu.push(future_husband[woman]);
future_husband[woman] = man;
future_wife[man] = woman;
}
void init(){
while(!qu.empty()) qu.pop();
}
void read(){
scanf("%d", &N);
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++)
scanf("%d", &pref[i][j]);
future_wife[i] = 0;
nxt[i] = 1;
qu.push(i);
}
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
int x;
scanf("%d", &x);
order[i][x] = j;
}
future_husband[i] = 0;
}
}
void solve(){
while(!qu.empty()){
int man = qu.front(); qu.pop();
int woman = pref[man][nxt[man]++];
if(!future_husband[woman] || order[woman][man] < order[woman][future_husband[woman]])
engage(man, woman);
else qu.push(man);
}
for(int i = 1; i <= N; i++) printf("%d\n", future_wife[i]);
}
int main()
{
int P;
scanf("%d", &P);
while(P--){
init();
read();
solve();
}
return 0;
}