稳定匹配算法 C 语言实现 - 框架

给定 n个男人,n个女人,每个男人都有一张对所有女人的偏爱表,每个女人都有一张对所有的男人的偏爱表,要求设计一算法,产生一稳定匹配。


匹配过程:

初始化所有的男人和女人都是自由的
	while(存在男人 m是自由的且还没对每个女人都求过婚)
		选择这样一个男人m
		令w 是m 的优先表中m 还没求过婚的最高排名的女人
			if w是自由的
				(m,v)变成约会状态
			else  w当前与 m’约会
				if w更爱 m’(对比m)
					m保持自由
				else w更爱 m(对比 m’)		
					(m,v)变成约会状态
					m’变成自由
				endif
			endif
	endwhile 



代码框架:

// Author: Zhang Yushan

#include 
#include 

#define person 4
#define true 1
#define false 0

// predilecations
char *maleTable[4][4][2] = {
	{{"l", 0},{"l",0}, {"m", 0}, {"h", 0}},
	{{"m", 0},{"m",0}, {"l", 0}, {"h", 0}},
	{{"h", 0},{"h",0}, {"l", 0}, {"m", 0}},
	{{"l", 0},{"m",0}, {"h", 0}, {"m", 0}}
};
char *femaleT[4][2] = {"mmlh","lmll","hhml","mlhh"};
int couple[4][4]={0};


int satisfied(int man)
{
	int proposed = true; // proposed to all women
	int isFree = true; // is free

	for (int j = 0; j < 3; j++){
		// if the man is free, continue to 
		// check if he hasn"t proposed to all women
		if (couple[man][j] != false){
			isFree = false; 
			break;
		} 
		if (maleTable[man][j][1] == false) {
			proposed = false;
			break;
		}
	}

	if ( isFree && !proposed) return false;
	else return true;
}



int main(int argc, char *argv[])
{
	if( argc == 1) printf("Default number of man is 4\n");
	else if (argc == 2) printf("Number of man is %d\n", (int)*argv[1]);
	else fprintf(stderr, "Usage: ./CG integer \n");

	int i, j = 0;

nextMan: if ( i < 3) i++; 
		 else return 0; // end if all men are checked

		// the man isn"t free or has proposed to all women
		 if (satisfied(j)) goto nextMan;
		 else printf("Continue\n");

		// find the women has highest favor
		//

		int woman = 1;
		int man = 0;
		for (; man < 3; man++){
			printf("man is %d", man);
			// no need to check this man 
			if ( man == i) continue;
			// the woman isn't free
			if ( couple[man][woman]) break;
			// the woman is free
			if( man == 3) {
				couple[i][woman] = 1;
				goto nextMan;
			}
		}
		printf("Compare\n");

	return 0;
}



你可能感兴趣的:(读书笔记)