问题背景
需要考虑的问题
算法描述
比较懒,怎么记录方便我就怎么来了,于是随手粘贴了图片
数据结构
1.将男士和女士对异性好感的排序表抽象成一个二维数组MP和WP
2.创建两个数组用来记录男士和女士是否单身,其中索引表示第几位男士,存储的值表示是否脱单。例如:
isManFree[0] = True # 表示第0位男士还是单身
3.设计男士对女士的追求表,记录男士有没有追过这位女士,二维表中女士表示横轴,男士表示纵轴
isManProposed[0][1] = True # 0号男士已经追求过1号女士
4.匹配对的存储match,match列表中存储的元素是一个个元组(m,w),match的索引表示男士的id
match[0] = (0,1) #0号男士和1号女士匹配 元组中的第一位为男士,第二位是女士,且男士的id==match的索引
Python实现
def stable_match(MP,WP):
n = len(MP)
isManFree = [True for i in range(n)] # 设置男士都为单身
isWomanFree = [True for i in range(n)] # 设置女士都为单身
isManProposed = [[False for i in range(n)] for j in range(n)] # 设置每一个男士对每一个女士都没有求过婚
match = [(-1,-1)]*n # 最后的匹配结果
while True in isManFree:
indexM = isManFree.index(True) # 获取第一个还是单身的男士
if False in isManProposed[indexM]: # 如果该男士还存在没有求过婚的女士
for i in range(n):
w = MP[indexM][i]
if not isManProposed[indexM][w]:
indexW = w
break
isManProposed[indexM][indexW] = True # 设置这位男士追求过这位女士
if isWomanFree[indexW]: # 女士还是单身
isWomanFree[indexW] = False #开始约会了!脱单
isManFree[indexM] = False #脱单
match[indexM] = (indexM,indexW) #生成一组匹配
else:# 被追求的女士早就名花有主,看男士的魅力大不大了
indexM_ = -1 # 该女士的现任,先赋值为-1
for j in range(n):
if match[j][1]==indexW: # 这位女士已经名花有主,找到她的主
indexM_ = j
break
if WP[indexW].index(indexM) < WP[indexW].index(indexM_):# 在这位女士的优先列表中判断,看后来的男士是否更加具有吸引力
isManFree[indexM_] = True
isManFree[indexM] = False
match[indexM] = (indexM,indexW)
print(match)
return match
def test():
MP = [
[0,1],
[1,0],
]
WP = [
[1,0],
[0,1],
]
stable_match(MP,WP)
def test2():
MP = [
[1,0,2],
[0,2,1],
[1,2,0],
]
WP = [
[0,2,1],
[1,0,2],
[0,1,2],
]
stable_match(MP,WP)
if __name__ == "__main__":
test()
test2()