稳定匹配 - Stable Matching

这篇文章将会对稳定匹配算法进行介绍及Python代码的实现,第一部分会针对稳定匹配的Gale-Shapley算法进行解析,第二部分就是用Python对该算法进行实现。

一、稳定匹配算法原理

1.1 介绍

稳定匹配(Stable Matching)问题就是假设现在有N个男生和N个女生跳舞选择伴侣,然后最开始的时候男、女生按照下面情况对彼此进行排序选择舞伴(见图1):

  • 每个男生都对女生按照最喜欢到最不喜欢进行排序;
  • 同样的,女生也是按照最喜欢的到最不喜欢对男生进行排序。

算法目标:每个男都找到唯一一个女舞伴,反之亦如此,从而达到了所谓的稳定匹配。

演示步骤:

1.2 伪代码(Gale-Shapley Algorithm)

 1 # 首先初始化所有男生的状态为自由
 2 initialize each person to be free
 3
 4 # 当男生没有未曾被匹配过并且也没有向所有其他女生寻求舞伴过时不断循环
 5 while some man m is not yet matched:
 6     # 每个男生按照对女生的喜欢程度选择舞伴
 7     w := m‘s most favroite woman to whom he has not yet proposed
 8     # 如果女生未被匹配到,则与男生进行配对
 9     if w is also not yet matched:
10         w and m are paired
11     # 如果女生与已匹配的男生相比更喜欢当前的这个男生,则拆散重新匹配
12     elif w favors m to her current matched m‘:
13         w and m are paired and m‘ is dis-matched
14     # 否则该女生拒绝成为男生的舞伴
15     else:
16         w rejects m
17 # 返回所有匹配成功的舞伴对
18 return matched pairs

二、Python代码实现

# -*- encoding: UTF-8 -*-
import copy

# 男的所期望的对象
manPrefers = dict((m, prefs.split(‘, ‘)) for [m, prefs] in (line.rstrip().split(‘: ‘)
                                for line in open(‘men.txt‘)))
# 女的所期望的对象
womenPrefers = dict((m, prefs.split(‘, ‘)) for [m, prefs] in (line.rstrip().split(‘: ‘)
                                for line in open(‘women.txt‘)))

men = sorted(manPrefers.keys())
women = sorted(womenPrefers.keys())

# 定义检测函数检测匹配的伴侣是否稳定
def check(engaged):
    inverseengaged = dict((v,k) for k,v in engaged.items())
    for w, m in engaged.items():
        shelikes = womenPrefers[w]
        shelikesbetter = shelikes[:shelikes.index(m)]
        helikes = manPrefers[m]
        helikesbetter = helikes[:helikes.index(w)]
        for man in shelikesbetter:
            womenOftheMan = inverseengaged[man]
            manLoves = manPrefers[man]
            if manLoves.index(womenOftheMan) > manLoves.index(w):
                print("%s 和 %s 更喜欢彼此相比起他们当前的伴侣: %s 和 %s" % (w, man, m, womenOftheMan))
                return False
        for woman in helikesbetter:
            manOfTheWomen = engaged[woman]
            womanLoves = womenPrefers[woman]
            if womanLoves.index(manOfTheWomen) > womanLoves.index(m):
                print("%s 和 %s 更喜欢彼此相比起他们当前的伙伴:%s 和 %s" % (m, woman, w, manOfTheWomen))
                return False
    return True

def stableMatching():
    free_men = men[:]
    engaged  = {}
    manPref_temp = copy.deepcopy(manPrefers)
    womenPref_temp = copy.deepcopy(womenPrefers)
    while free_men:
        man = free_men.pop(0)
        manList = manPref_temp[man]
        woman = manList.pop(0)
        fiance = engaged.get(woman)
        if not fiance:
            engaged[woman] = man
            print("  %s 和 %s 成为伴侣" % (man, woman))
        else:
            womenList = womenPref_temp[woman]
            if womenList.index(fiance) > womenList.index(man):
                engaged[woman] = man
                print("  %s 舍弃 %s 而和 %s 成为伴侣" % (woman, fiance, man))
                if manPref_temp[fiance]:
                    free_men.append(fiance)
            else:
                if manList:
                    free_men.append(man)
    return engaged

if __name__ == ‘__main__‘:
    print(‘\n伴侣匹配:‘)
    engaged = stableMatching()

    print(‘\n伴侣匹配:‘)
    print(‘  ‘ + ‘,\n  ‘.join(‘%s 和 %s 成为伴侣‘ % couple for couple in sorted(engaged.items())))
    print()
    print(‘伴侣稳定性检测通过‘ if check(engaged) else ‘伴侣稳定性检测不通过‘)

    print(‘\n\n因交换而产生伴侣搭配错误‘)
    engaged[women[0]], engaged[women[1]] = engaged[women[1]], engaged[women[0]]
    for woman in women[:2]:
        print(‘  %s 现在和 %s 成为伴侣‘ % (woman, engaged[woman]))
    print()
    print(‘伴侣稳定性检测通过‘ if check(engaged) else ‘伴侣稳定性检测不通过‘)

  

原文地址:https://www.cnblogs.com/jielongAI/p/9463029.html

时间: 2024-08-26 13:50:44

稳定匹配 - Stable Matching的相关文章

Stable Matching 稳定匹配 婚姻算法 shapley 算法

作者:jostree  转载请注明出处 http://www.cnblogs.com/jostree/p/4051286.html 稳定匹配问题:有N男N女,每个人对于异性都一个排名,先需要得到一种稳定的匹配,即不会出现一个匹配中的人与另一个匹配中的异性对对方的排名均高于目前配对的人的排名. shapley算法: 每次取出一个单身男生,让他向没有拒绝过她的女生中其排名最高人表白,若该女生没有对象则配对成功,否则与其当前的对象排名进行对比,如果当前对象排名较高,则拒绝表白男生,否则dump掉目前对

Stable Matching Problem

The Stable Matching Problem originated, in part, in 1962, when David Gale and Lloyd Shapley, two mathematical economists, asked the question: Could one design a college admissions process, or a job recruiting process, that was self-enforcing? What di

Demystify 稳定匹配理论和圈圈图

你知道这个图的意义吗? 实验经济学里有个人物Al Roth,2012年获得诺贝尔经济奖,获奖领域是稳定匹配理论及其应用. 稳定匹配啥意思?考虑一个虚拟的雇佣市场问题,N个企业和N个工人的一对一匹配问题,假设每个企业对每个工人都有一个打分,分数越高代表某企业在可能的情况下会优先选择那个工人.同样,每个工人也给每个企业打分.现在如何给这些工人和企业做一个一对一的匹配?这是一个双向选择问题,一个公平的匹配应该是稳定匹配,具有如下特性:稳定匹配中的双方,尽管对方未必是最中意的那个,但他(它)又无法和任何

稳定匹配

问题背景: n个男生和m个女生进行匹配约会,当然一个男生至多和一个女生约会,一个女生也至多和一个男生约会,并且每个男生心中都有一个对女生的排名表,即表示了这个男生更愿意与哪个女生约会,不同男生的排名表不一定相同,每个女生也都有一个对男生的排名表.现在要求你求一个匹配,这个匹配不含 不稳定因素. 不稳定因素:一个男生A,一个女生B,A与A‘匹配,B与B’匹配,但A更愿意与B匹配,B也更愿意与A匹配,具有这种性质的(A,B)就被称为不稳定因素. 数学模型: 两个点集:M,W,M={m1,m2,m3…

Stable Matching (Gale Sharpley Algorithm)

以下为数据生成函数,生成boys_rankings.txt 和 girls_rankings.txt #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <sstream> #include <algorithm> #include <vector> #inc

opencv笔记(二十二)——模板匹配 template matching

模板匹配就是在给定一幅图像和一幅模板(一般模板比图像的尺寸小很多)的情况下,找到这个图像中最最相似于模板的位置,比如 第一幅是给定的图片,第二幅是模板,第三幅就是搜索到的匹配的位置. 这个搜索的过程,我没有在源码中求索,但是根据tutorial,应该是采用sliding window的方法,利用滑动的窗口,逐像素进行匹配.这个逐像素的意思,就是锚定某个像素之后,在这个像素的右边和下方,以template的宽度和高度的距离的范围内,进行模板与图像的相似度计算. 这种方法和行人检测中常用的方法类似.

【算法】恋爱中的博弈论(stable matching)(附带源码)

思路源自知乎:恋爱中有那些博弈?,主要是@尼克余 的回答.感谢他.然后原文有些描述不清楚的,我直接就按照我的理解补充上去了. 注:本文采用C#实现 首先假设一个虚拟世界,这个世界中分别有N个男生,N个女生,男生与女生数量完全一样,男生女生都有一个心仪对象列表,不同的人的心仪对象列表都是随机的,在心仪对象列表排名越前面,说明对于他(她)来说越喜欢.男生能向女生表白,女生不能向男生表白,女生能接受或者拒绝男生的表白. 男生首先会向对他最喜欢的女生表白,然后是次喜欢的,依次下去表白.而女生则通过对表白

[Swift]LeetCode1023. 驼峰式匹配 | Camelcase Matching

A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.) Given a list of queries, and a pattern, return an an

HDU 1522 Marriage is Stable 【稳定婚姻匹配】(模板题)

<题目链接> 题目大意: 给你N个男生和N个女生,并且给出所有男生和女生对其它所有异性的喜欢程度,喜欢程度越高的两个异性越容易配对,现在求出它们之间的稳定匹配. 解题分析: 稳定婚姻问题的模板题,需要用到Gale_Shapley算法,GS算法讲解  >>> 这个算法还是很直观的. 1 #include <iostream> 2 #include <cstring> 3 #include <stack> 4 #include <stri