最近因为课程需要,看了看婚姻稳定匹配问题,用了两天把代码写完了。
具体问题就不详细写了,这里给出参看的网址。
整个思路结合着老师的课件和这篇文章,用C语言完成了整个代码。
//
// main.c
// MarriageMatch
//
// Created by shadowdai on 11-11-27.
// Copyright (c) 2011年 BUPTSSE. All rights reserved.
//
#include
int main (int argc, const char * argv[])
{
int manPerference[3][3];//下标表示女士的号码,1-5,储存的值表示对该女士的好感度
int womanPerference[3];//表示5位女士选择的男士
int manMostLike[3];//表示男士最喜欢的女士
int manCurrentMatch[3];//表示当前男士的配对对象
int womanCurrentMatch[3];//表示当前女士的配对对象
int womanBool[3];//表示女士的配对状况,0表示未配对,1表示已经配对
int manBool[3];//表示男士的配对状况
int MatchNumber = 0;
int i,j;
int max,Max;
printf("输入男士的好感度排名:(数字越大表示越喜欢)\n");
for (i = 0; i < 3; i++) {
printf("男士%d:\n",i+1);
for (j = 0; j < 3; j++) {
scanf("%d", &manPerference[i][j]);
}
}
//女士选择男士
for (i = 0; i < 3; i++) {
max = 0;
womanBool[i] = 0;
manBool[i] = 0;
Max = manPerference[0][i];
for ( j = 0; j < 3; j++) {
if (manPerference[j][i] > Max) {
max = j;
Max = manPerference[j][i];
}
}
womanPerference[i] = max;
}
printf("\n女士的选择:\n");
for (i = 0; i < 3; i++) {
printf("女士No.%d选择%d\n",i+1, womanPerference[i]+1);
}
//选出男士最喜欢的女士
for ( i = 0; i < 3; i++) {
for ( j = 0; j < 3; j++) {
if (manPerference[i][j] == 3) {
manMostLike[i] = j;
}
}
}
printf("\n男士最喜欢的女士:\n");
for (i = 0; i < 3; i++) {
printf("No.%d男士选择了No.%d女士\n",i+1,manMostLike[i]+1);
}
printf("\n");
while (MatchNumber != 3) {
//根据男士和女士的选择的对象进行匹配
for (i = 0; i < 3; i++) {
if (womanBool[manMostLike[i]] == 0 && manBool[i] == 0) {
//如果该男士选择的女士没有配对,那么将他们配对
manCurrentMatch[i] = manMostLike[i];
womanCurrentMatch[manMostLike[i]] = i;
womanBool[manMostLike[i]] = 1;
manBool[i] = 1;
MatchNumber += 1;
printf("No.%d男士与No.%d女士配对,两位在此之前均没有配对。\n", i+1, manCurrentMatch[i]+1);
}
else if(womanBool[manMostLike[i]] == 1 && manBool[i] == 0){
//如果该女士已经配对,则需要比较该女士更喜欢哪位男士
if (womanPerference[manMostLike[i]] == i) {
//如果该女士选择的是该男士,那么直接进行配对
manCurrentMatch[i] = manMostLike[i];
womanCurrentMatch[manMostLike[i]] = i;
womanBool[manMostLike[i]] = 1;
manBool[i] = 1;
MatchNumber += 1;
printf("No.%d男士与No.%d女士配对,虽然该女士之前有配对对象,但是选择了该男士。\n", i+1, manCurrentMatch[i]+1);
}
else if( manPerference[i][manMostLike[i]] > manPerference[womanCurrentMatch[i]][manMostLike[i]]){
//如果该女士没有选择该男士,但是该女士现在的配对对象的优先级低于该男士,则将他们配对
manBool[womanCurrentMatch[manMostLike[i]]] = 0;
manCurrentMatch[i] = manMostLike[i];
womanCurrentMatch[manMostLike[i]] = i;
womanBool[manMostLike[i]] = 1;
manBool[i] = 1;
printf("No.%d男士与No.%d女士配对,虽然该女士之前有配对对象,但是更喜欢该男士。\n", i+1, manCurrentMatch[i]+1);
}
else{
//如果该女士没有选择该男士,并且该男士的优先级低于该女士,那么该女士拒绝该男士
for ( j = 0; j < 3; j++) {
//该男士被拒绝之后,只能寻找下一个最喜欢的女士
if (manPerference[i][j] == manPerference[i][manMostLike[i]] -1) {
manMostLike[i] = j;
printf("No.%d男士没有配对成功,所以降低了选择的人士,现在他最喜欢No.%d女士。\n",i+1, j+1);
break;
}
}
}
}
else if(manBool[i] == 1){
printf("No.%d男士已经配对成功。\n",i+1);
}
}
}
for (i = 0; i < 3; i++) {
printf("\nNo.%d男士与No.%d女士配对成功!\n", i+1, manCurrentMatch[i]+1);
}
} 如果有需要,请标明转载,谢谢!