[HDU 1914] The Stable Marriage Problem (稳定婚姻问题)

HDU - 1914

稳定婚姻问题
每个男士对所有女士有个喜欢程度,每个女士对所有男士也有个喜欢程度
使男女两两配对,使得找不到一对男女,满足
他们不相匹配,且他们喜欢对方都超过喜欢自己现有的另一半


稳定婚姻问题的求解思路,分三个步骤
每个尚未配对的男士寻找当前他最喜欢的女士
1. 若当前女士未配对,则配对
2. 若当前女士已配对,且她更喜欢后来的男士,则她抛弃未婚夫
3. 当前男士求婚失败,再次进入单身队列
这样配对出来的组合是 male-optimal的

证明待补充。

#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef double DBL;
typedef long double LDBL;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) (a*a)

const int maxn=26;
int N;
int male[maxn][maxn];
int nxt[maxn];
int like[maxn][maxn];
int hus[maxn],wif[maxn];
bool name[2][maxn];
queue<int> alone;

void engage(int,int);

int main()
{
    int T;
    scanf("%d", &T);
    for(int ck=1; ck<=T; ck++)
    {
        MST(hus,-1);MST(wif,-1);CLR(name);
        scanf("%d", &N);
        for(int i=0; i<N; i++) {char x;scanf(" %c", &x);name[0][x-'a']=1;}
        for(int i=0; i<N; i++) {char x;scanf(" %c", &x);name[1][x-'A']=1;}
        for(int i=0; i<N; i++)
        {
            char now,pref[maxn];
            scanf(" %c:%s", &now, pref);
            for(int j=0; j<N; j++) male[now-'a'][j]=pref[j]-'A';
            nxt[now-'a']=0;
            alone.push(now-'a');
        }
        for(int i=0; i<N; i++)
        {
            char now,pref[maxn];
            scanf(" %c:%s", &now, pref);
            for(int j=0; j<N; j++) like[now-'A'][pref[j]-'a']=j;
        }

        while(alone.size())
        {
            int m=alone.front();alone.pop();
            int f=male[m][nxt[m]];
            nxt[m]++;
            if(hus[f]==-1) engage(m,f);
            else if( like[f][hus[f]] > like[f][m] ) engage(m,f);
            else {alone.push(m);}
        }

        for(int i=0; i<maxn; i++)
        {
            if(name[0][i])
            {
                printf("%c %c\n", i+'a', wif[i]+'A');
            }
        }
        if(ck<T) puts("");
    }
    return 0;
}

void engage(int male, int female)
{
    if(~hus[female])
    {
        alone.push(hus[female]);
        wif[hus[female]]=-1;
    }
    hus[female]=male;
    wif[male]=female;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值