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;
}
稳定匹配算法的实现与应用
本文详细介绍了稳定匹配算法的实现过程,并通过C++代码展示了如何在实际场景中应用该算法解决男性最优婚姻匹配问题。
1万+

被折叠的 条评论
为什么被折叠?



