稳定婚配问题:n个男生n个女生。当中每一个人都有自己心仪的列表。

问怎样达成稳定的匹配(比方, b想B求婚,可是B已有的对象的优先级高于b,此时b的魅力不足以拆散B所处的那一对,即达到稳定状态。)

(Gale_Shapley algorithm)整体策略:男士负责求婚,女士负责接受或者拒绝。

题目原型: HDUOJ 1914 The Stable Marriage Problem

下面为数据生成函数,生成boys_rankings.txt 和 girls_rankings.txt

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <string>
  6. #include <sstream>
  7. #include <algorithm>
  8. #include <vector>
  9. #include <ctime>
  10. #include <fstream>
  11.  
  12. using namespace std;
  13.  
  14. vector<string> gen_boys(int number)
  15. {
  16. vector<string> result;
  17. for(int i = 0; i < number; i++){
  18. string boy = "B";
  19. string s;
  20. stringstream ss;
  21. ss << i;
  22. ss >> s;
  23. boy.append(s);
  24. result.push_back(boy);
  25. }
  26. return result;
  27. }
  28.  
  29. vector<string> gen_girls(int number)
  30. {
  31. vector<string> result;
  32. for(int i = 0; i < number; i++){
  33. string boy = "G";
  34. string s;
  35. stringstream ss;
  36. ss << i;
  37. ss >> s;
  38. boy.append(s);
  39. result.push_back(boy);
  40. }
  41. return result;
  42. }
  43.  
  44. vector<string> gen_ranking(vector<string> candidate)
  45. {
  46. random_shuffle(candidate.begin(), candidate.end());
  47. return candidate;
  48. }
  49.  
  50. void write_rankings(vector<string> people, vector<vector<string> > rankings, string out_file)
  51. {
  52. ofstream ofs(out_file.c_str());
  53. if(ofs.fail()){
  54. cerr << "Error: " << out_file << endl;
  55. return;
  56. }
  57. for(int i = 0; i < people.size(); i++){
  58. ofs << people[i] << ":";
  59. for(int j = 0; j < rankings[i].size(); j++){
  60. ofs << " " << rankings.at(i).at(j);
  61. }
  62. ofs << endl;
  63. }
  64. ofs.close();
  65. }
  66.  
  67. int main(int argc, char ** argv)
  68. {
  69. srand(time(NULL));
  70. int n = 200;
  71. vector<string> boys = gen_boys(n);
  72. vector<string> girls = gen_girls(n);
  73. vector<vector<string> > boys_rankings;
  74. vector<vector<string> > girls_rankings;
  75. for(int i = 0; i < n; i++){
  76. boys_rankings.push_back(gen_ranking(girls));
  77. girls_rankings.push_back(gen_ranking(boys));
  78. }
  79. write_rankings(boys, boys_rankings, "boys_rankings.txt");
  80. write_rankings(girls, girls_rankings, "girls_rankings.txt");
  81. return 1;
  82. }

下面为Gale_Sharpley算法实现:

  1. /******************************************************
  2. * Projects : Implementation of Gale_Shapley algorithm
  3. * Author : johnsondu
  4. * Time : 2014-10-20 21:18
  5. *******************************************************/
  6. #include <iostream>
  7. #include <cstdio>
  8. #include <cmath>
  9. #include <algorithm>
  10. #include <fstream>
  11. #include <map>
  12. #include <vector>
  13. #include <cstring>
  14. #include <string>
  15. using namespace std;
  16.  
  17. // The max size of the number of the boy.
  18. const int MAXN = 1000;
  19. // STL map, map boy's name to integer ID
  20. map<string, int> boy;
  21. // STL map, map girl's name to integer ID
  22. map<string, int> girl;
  23. // STL map, map corresponding boy's integer id to original string name
  24. map<int, string> boyName;
  25. // STL map, map corresponding girl's integer id to original string name
  26. map<int, string> girlName;
  27. // boy's preference ranking list
  28. int boysRankings[MAXN][MAXN];
  29. // girl's preference ranking list
  30. int girlsRankings[MAXN][MAXN];
  31. // the partner that boy matched. if no, marked as -1
  32. int boysPartner[MAXN];
  33. // the partner that girl matched. if no, marked as -1
  34. int girlsPartner[MAXN];
  35.  
  36. /*******************************************************
  37. * function description:
  38. * let every boy and girl have it's own integer identity.
  39. * key variable: <string, int>(map string name to integer
  40. * id), <int, string>(map integer id to original string
  41. * name)
  42. ********************************************************/
  43. void SerialNumber(int &n)
  44. {
  45. ifstream in1("boys_rankings.txt");
  46. ifstream in2("girls_rankings.txt");
  47. string str;
  48.  
  49. int idb = 0; // boy's id
  50. int idg = 0; // girl's id
  51.  
  52. while(getline(in1, str)){
  53. string name = "";
  54. int i = 0;
  55. // get boys's name
  56. while(str[i] != ':') name += str[i ++];
  57. // map string to int.
  58. boy[name] = idb ;
  59. boyName[idb] = name;
  60. idb ++;
  61. // get the number of boys.
  62. n ++;
  63. }
  64.  
  65. while(getline(in2, str)){
  66. string name = "";
  67. int i = 0;
  68. // get boys's name
  69. while(str[i] != ':') name += str[i ++];
  70. // map string to int.
  71. girl[name] = idg;
  72. girlName[idg] = name;
  73. idg ++;
  74. }
  75. return;
  76. }
  77.  
  78. /*********************************************
  79. * function description:
  80. * Rereading two files, and get corresponding
  81. * preference list of boys and girls. Save it
  82. * in two dimension array: girlsRankings and
  83. * boysRankings.
  84. *******************************************/
  85. void GetRankings(const int n)
  86. {
  87. ifstream in1("boys_rankings.txt");
  88. ifstream in2("girls_rankings.txt");
  89. string str;
  90.  
  91. // boy's id.
  92. int id = 0;
  93. while(getline(in1, str)){
  94. string gname;
  95. int i = 0;
  96.  
  97. int cnt = 0;
  98. while(str[i] != ' ') i ++;
  99. if(str[i] == ' ') i ++;
  100. for(; i < str.size();)
  101. {
  102. gname = "";
  103. while(str[i] != ' ' && i < str.size()) {
  104. gname += str[i];
  105. i ++;
  106. }
  107. boysRankings[id][cnt ++] = girl[gname];
  108. if(str[i] == ' ') i ++;
  109. }
  110. id ++;
  111. }
  112.  
  113. // girls id;
  114. id = 0;
  115.  
  116. while(getline(in2, str)){
  117.  
  118. string bname;
  119. // string size index.
  120. int i = 0;
  121. // the rankings in the girl's list.
  122. int cnt = 0;
  123. // prefix guarantee
  124. while(str[i] != ' ') i ++;
  125. if(str[i] == ' ') i ++;
  126. for(; i < str.size();)
  127. {
  128. bname = "";
  129. while(str[i] != ' ' && i < str.size()) {
  130. bname += str[i];
  131. i ++;
  132. }
  133. girlsRankings[id][cnt ++] = boy[bname];
  134. if(str[i] == ' ') i ++;
  135. }
  136. id ++;
  137. }
  138. return ;
  139. }
  140.  
  141. /*************************************
  142. * function description:
  143. * set status for boys and girls,
  144. * marked -1, no partner.
  145. **************************************/
  146. void InitStatus(const int n)
  147. {
  148. for(int i = 0; i < n; i ++)
  149. {
  150. boysPartner[i] = -1;
  151. girlsPartner[i] = -1;
  152. }
  153. }
  154.  
  155. /****************************************
  156. * function description:
  157. * when one boy propose to one girl, and
  158. * that girl already have a partner, this
  159. * function is used for get ratings of
  160. * two boys in that girl's preference list.
  161. *****************************************/
  162. int GetId(int boyId, int gId, const int n)
  163. {
  164. for(int i = 0; i < n; i ++)
  165. {
  166. if(girlsRankings[gId][i] == boyId) return i;
  167. }
  168. return -1;
  169. }
  170.  
  171. /****************************************
  172. * function description:
  173. * once a man have dumped by a girl, set
  174. * his status to no partner, and set his
  175. * preference list of that girl as -1,
  176. * stand for have been proposed before.
  177. *****************************************/
  178. void SetStatus(int boyId, int girlId, const int n)
  179. {
  180. boysPartner[boyId] = -1;
  181. for(int i = 0; i < n; i ++)
  182. if(boysRankings[boyId][i] == girlId){
  183. boysRankings[boyId][i] = -1;
  184. return;
  185. }
  186. }
  187.  
  188. /****************************************
  189. * function description:
  190. * Implementation of Gale_Shapley algorithm
  191. *****************************************/
  192. void StableMatch(const int n)
  193. {
  194. InitStatus(n);
  195.  
  196. while(true)
  197. {
  198. bool flag = false;
  199. bool endOfFor = false;
  200. // guarantee all the boys have a partner.
  201. for(int i = 0; i < n; i ++){
  202. if(boysPartner[i] == -1 || girlsPartner[i] == -1)
  203. {
  204. flag = true;
  205. break;
  206. }
  207. }
  208. if(!flag) break;
  209.  
  210. // for boy who have no partner.
  211. for(int i = 0; i < n; i ++)
  212. {
  213. if(boysPartner[i] == -1){
  214. for(int j = 0; j < n; j ++){
  215. // Since in the list of preference, j had rejected before.
  216. if(boysRankings[i][j] == -1) continue;
  217.  
  218. // if j have no partner, then accept.
  219. if(girlsPartner[boysRankings[i][j]] == -1){
  220. boysPartner[i] = boysRankings[i][j];
  221. girlsPartner[boysRankings[i][j]] = i;
  222. endOfFor = true;
  223. break;
  224. }
  225. else{ // judge whether match is stable or not
  226. int useId = GetId(girlsPartner[boysRankings[i][j]], boysRankings[i][j], n);
  227. int curId = GetId(i, boysRankings[i][j], n);
  228. // if not stable
  229. if(curId < useId){
  230. // girl's partner's list, set -1 to mean the girl have rejected.
  231. SetStatus(girlsPartner[boysRankings[i][j]], boysRankings[i][j], n);
  232. boysPartner[i] = boysRankings[i][j];
  233. girlsPartner[boysRankings[i][j]] = i;
  234. endOfFor = true;
  235. break;
  236. }
  237. }
  238. }
  239. }
  240. // find a partner, break out of the loop.
  241. if(endOfFor) break;
  242. }
  243. }
  244. }
  245.  
  246. /****************************************
  247. * function description:
  248. * print out result.
  249. *****************************************/
  250. void Print(const int n)
  251. {
  252. freopen("result.txt", "w", stdout);
  253. cout << "The Matching Results are follows:" << endl;
  254. for(int i = 0; i < n; i ++){
  255. cout << boyName[i]
  256. << "--" << girlName[boysPartner[i]] << " " << endl;
  257. }
  258. }
  259.  
  260. /****************************************
  261. * function description:
  262. * Main function
  263. *****************************************/
  264. int main()
  265. {
  266. int n = 0;
  267. // let every boy and girl have it's own identity.
  268. // and get integer ranking array list.
  269. SerialNumber(n);
  270. // get rankings.S
  271. GetRankings(n);
  272. // Stable match
  273. StableMatch(n);
  274. // Print solution
  275. Print(n);
  276.  
  277. return 0;
  278. }

Stable Matching (Gale Sharpley Algorithm)的更多相关文章

  1. 稳定匹配 - Stable Matching

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

  2. xshell SSH 连接出现 outgoing encryption ,或者no matching host key algorithm found错误的解决

    首先看看xshell的使用版本,如果是xshell 4,提示的信息为:no matching host key algorithm found 如果是xshell 5,提示的是: outgoing e ...

  3. Maximum Cardinality Bipartite Matching: Augmenting Path Algorithm

    http://www.csie.ntnu.edu.tw/~u91029/Matching.html int nx,ny; int mx[N],my[N]; bool vy[N]; bool g[N][ ...

  4. XShell 无法匹配的outgoing encryption算法 ,No matching outgoing encryption algorithm found

    在链接的属性(SSH -> 安全性) 的加密算法列表中选择 aes256-ctr, mac加密列表中选择hmac-sha2-256,保存即可 To enable hmac-sha2-256 an ...

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

    作者:jostree  转载请注明出处 http://www.cnblogs.com/jostree/p/4051286.html 稳定匹配问题:有N男N女,每个人对于异性都一个排名,先需要得到一种稳 ...

  6. [algorithm] My rookie plan to start

    若干年后,经验有一些,但根基不牢靠.[algorithm] series 借助学习Standard Template Library: Algorithms的这段时期,在自己的算法和c++基础方面加些 ...

  7. Shine we together: A innovative dating site using 2012 Nobel Laureate Roth's algorithm

    Abstract Our dating site introduced scoring and its related functionalities innovatively, conforming ...

  8. Algorithm | Sort

    Bubble sort Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algo ...

  9. 近年Recsys论文

    2015年~2017年SIGIR,SIGKDD,ICML三大会议的Recsys论文: [转载请注明出处:https://www.cnblogs.com/shenxiaolin/p/8321722.ht ...

随机推荐

  1. 学习参考《TensorFlow深度学习》高清中文版PDF+英文版PDF+源代码

    我们知道,TensorFlow是比较流行的深度学习框架,除了看手册文档外,推荐大家看看<Tensorflow深度学习>,共分5方面内容:基础知识.关键模块.算法模型.内核揭秘.生态发展.前 ...

  2. oracle 正序 逆序 排序查询

    正序:从小到大 order by t.id asc 逆序:从大到小 order by t.id desc

  3. 【CS Round #37 (Div. 2 only) A】Boring Number

    [Link]:https://csacademy.com/contest/round-37/task/boring-number/ [Description] 让你找离平均数最近的一个数的下标; [S ...

  4. C# async/await异步编程深入理解

    异步函数简介 一般指 async 修饰符声明得.可包含await表达式得方法或匿名函数. 声明方式 异步方法的声明语法与其他方法完全一样, 只是需要包含 async 关键字.async可以出现在返回值 ...

  5. 云计算时代告别phpMyAdmin

    云计算时代告别phpMyAdmin phpMyAdmin是一款很经典的MySQL数据库管理工具,在云计算快速发展的今天,phpMyAdmin交互老旧.已经不能适应时代步伐.因此有很多人開始选择一些更高 ...

  6. cocos2d-x的声音控制

    声音控制SimpleAudioEngine是单例.下面是其方法. [cpp] view plaincopy //获得SimpleAudioEngine的实例 static SimpleAudioEng ...

  7. ajax ---- json 和 xml 区别

    2.XML和JSON优缺点 (1).XML的优缺点<1>.XML的优点 A.格式统一,符合标准: B.容易与其他系统进行远程交互,数据共享比较方便.<2>.XML的缺点 A.X ...

  8. 网页中插入javascript的几种方法

    网页中插入javascript的方法常见的有两种: 一.直接使用html标记 JavaScript 可以出现在 html的任意地方.使用标记<script>…</script> ...

  9. Cisco交换机SPAN&RSPAN调试实录

    Cisco交换机SPAN&RSPAN设置实录   本文出自 "李晨光原创技术博客" 博客,请务必保留此出处http://chenguang.blog.51cto.com/3 ...

  10. Server.MapPath()的用法

    http://blog.csdn.net/qiuhaifeng_csu/article/details/19416407 Server.MapPath(string path)作用是返回与Web服务器 ...