稳定婚姻问题

本文详细介绍了稳定匹配算法的实现过程,并通过C++代码展示了如何在实际场景中应用该算法解决男性最优婚姻匹配问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

It is commonly stated as: Given n men and n women, where each person has ranked all members of the opposite sex with a unique number between 1 and n in order of preference, marry the men and women off such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are "stable".

http://hi.baidu.com/fandywang%5Fjlu/blog/item/7c20b0d4c9149207a18bb706.html

Algorithm function stableMatching {    Initialize all m ∈ M and w ∈ W to free    while ? free man m who still has a woman w to propose to {       w = m's highest ranked such woman       if w is free         (m, w) become engaged       else some pair (m', w) already exists         if w prefers m to m'           (m, w) become engaged           m' becomes free         else           (m', w) remain engaged    }}以上算法是 male-optimal We say that the marriage between man A and woman B is feasible if there exists a stable pairing in which A and B are married. When we say a pairing is male-optimal, we mean that every man is paired with his highest ranked feasible partner. Similarly, a female-pessimal pairing is one in which each female is paired with her lowest ranked feasible partner. Ladies' Choice#include <iostream>
#include <queue>
using namespace std;
short girlboylikegirl[1001][1001],boyparterboylikegirl[1001][1001],girlparter[1001],ba[1001];
short boylikegirl[1001][1001],cur[1001];
bool boyfree[1001];
queue<int> q;
int main()
{
int p,n,i,j;
scanf("%d",&p);
while(p--)
{
   scanf("%d",&n);
   for(i=1;i<=n;i++)
   {
    for(j=0;j<n;j++)
     scanf("%d",&girlboylikegirl[i][j]);
   }
   for(i=1;i<=n;i++)
   {
    for(j=0;j<n;j++){
     scanf("%d",&boyparterboylikegirl[i][j]);
     boylikegirl[i][boyparterboylikegirl[i][j]]=j;
    }
   }
   memset(boyfree,0,sizeof(boyfree));
   memset(cur,0,sizeof(cur));
   for(i=1;i<=n;i++)
    q.push(i);
   while(!q.empty())
   {
    i=q.front();
    q.pop();
    for(j=cur[i];j<n;j++)
    {
     if(boyfree[girlboylikegirl[i][j]]==0)
     {
      girlparter[i]=girlboylikegirl[i][j];
      ba[girlboylikegirl[i][j]]=i;
      boyfree[girlboylikegirl[i][j]]=1;
      cur[i]=j+1;
      break;
     }
     else if(boylikegirl[girlboylikegirl[i][j]][i]<boylikegirl[girlboylikegirl[i][j]][ba[girlboylikegirl[i][j]]])
     {
      girlparter[i]=girlboylikegirl[i][j];
      q.push(ba[girlboylikegirl[i][j]]);
      ba[girlboylikegirl[i][j]]=i;
      cur[i]=j+1;
      break;
     }
    }
   }
   for(i=1;i<=n;i++)
    printf("%d\n",girlparter[i]);
}
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值