The Stable Matching/Marriage Problem稳定匹配
重要的是要根据题目设置变量来描述问题,也就是建模
根据书上的算法步骤:
while 存在男人m是自由的且还没对每个女人都求过婚
选择这个男人m
令w是m的优先表中还没求过婚的最高排名的女人
if w是自由的
(m,w)变成约会状态
else w当前与m1约会
if w更偏爱m1而不爱m
m保持自由
else w更偏爱m而不爱m1
(m,w)变成约会状态
m1变成自由
endif
endif
endwhile
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main{
/**
* @param args
*/
public static void main(String[] args) {
int N, K;
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
K = sc.nextInt();//男的编号
int[][] man = new int[N][N];//男人的对女人的优先顺序
int[][] woman = new int[N][N];
int[][] womenOrder = new int[N][N];
for (int i = 0; i<N; i++){
for (int j = 0; j<N; j++){
man[i][j] = sc.nextInt();
}
}
for (int i = 0; i<N; i++){
for (int j = 0; j<N; j++){
woman[i][j] = sc.nextInt();
}
}
for (int i = 0; i<N; i++){
for (int j = 0; j<N; j++){
//第i个女生喜欢的男生women[i][j]排号为
womenOrder[i][woman[i][j]] = j;
}
}
//还未配对的男生
Queue<Integer> freeMan = new LinkedList<>();
for (int i = 0; i<N; i++){
freeMan.offer(i);
}
int sboy = -1;
int[] manChoice = new int[N];//第i个男性的选择,都是选择最喜欢的,也就是排序中的第一个
int[] womanChoice = new int[N];//第i个女性的选择,女生最开始是自由的
//初始化男的选择,选最好的
for (int i = 0; i<N; i++){
manChoice[i] = 0;
}
//下标表示女生的编号
for (int i = 0; i<N; i++){
womanChoice[i] = -1;
}
while (!freeMan.isEmpty()){
//boy是男生编号
int boy = freeMan.remove();
for (int i = 0; i<N; i++){
//该女生没有男朋友
if (womanChoice[man[boy][i]]==-1){
manChoice[boy] = i;
womanChoice[man[boy][i]] = womenOrder[man[boy][i]][boy];
break;
}
else{
//序号小,排名靠前
if (womenOrder[man[boy][i]][boy] < womanChoice[man[boy][i]]){
sboy = woman[man[boy][i]][womanChoice[man[boy][i]]];
//将被抛弃的重新加到队列
freeMan.offer(sboy);
manChoice[sboy] = 0;
manChoice[boy] = i;
womanChoice[man[boy][i]] = womenOrder[man[boy][i]][boy];
break;
}
}
}
}
System.out.println(man[K][manChoice[K]]);
}
}
都有注释,应该比较好理解(为啥用Java因为C已经不会了)