Loading [Contrib]/a11y/accessibility-menu.js
$\newcommand{\O}{\mathrm{O}}$ My Algorithm : kopricky アルゴリズムライブラリ

kopricky アルゴリズムライブラリ

Gale Sharpley

コードについての説明(個人的メモ)

$2$ 種類のグループ(男女など)の間での安定マッチングを求めるアルゴリズム. このような問題を安定結婚問題とも言う.
男女それぞれが相手のグループのメンバーに対しての優先順位を持っているとする. ここである男 $i$, 女 $j$ について $i$ が $j$ よりも優先順位の低いメンバーとマッチングしていて, $j$ も $i$ より優先順の低いメンバーとマッチングしているとき、このようなペアを blocking pair とする.
このような blocking pair の存在しないマッチングを安定マッチングと呼ぶ. このようなマッチングは常に存在することが GaleSharpley のアルゴリズムから構成的に分かる.
元論文は "College Admissions and the Stability of Marriage" [Gale Sharpley 1962]

(関数)
solve$(mpref, wpref)$ : 優先度の高い順に相手の ID を格納した行列を $2$ つ渡す(男性が申し込む場合の実装である).

時間計算量: $\O (n^2)$

コード

  1. class GaleSharpley
  2. {
  3. public:
  4. GaleSharpley(){}
  5. vector<int> solve(const vector<vector<int> >& mpref, const vector<vector<int> >& wpref)
  6. {
  7. int n = mpref.size();
  8. vector<vector<int> > worder(n, vector<int>(n));
  9. stack<int> single;
  10. for(int i = 0; i < n; ++i){
  11. single.push(i);
  12. for(int j = 0; j < n; ++j){
  13. worder[i][wpref[i][j]] = j;
  14. }
  15. }
  16. vector<int> id_pos(n, 0);
  17. vector<int> wtom(n, -1);
  18. while(!single.empty()){
  19. int man = single.top();
  20. single.pop();
  21. while(true){
  22. int woman = mpref[man][id_pos[man]++];
  23. if(wtom[woman] < 0){
  24. wtom[woman] = man;
  25. break;
  26. }else if(worder[woman][wtom[woman]] > worder[woman][man]){
  27. single.push(wtom[woman]);
  28. wtom[woman] = man;
  29. break;
  30. }
  31. }
  32. }
  33. vector<int> mtow(n);
  34. for(int i = 0; i < n; ++i)
  35. mtow[wtom[i]] = i;
  36. return mtow;
  37. }
  38. };

verify 用の問題

verify していません(verify 問題を知らない)