hdu 1522Marriage is Stable(稳定婚姻问题)

来一发模板题。。。貌似不存在无解情况。。。

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<fstream>
#include<sstream>
#include<bitset>
#include<vector>
#include<string>
#include<cstdio>
#include<cmath>
#include<stack>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define FF(i, a, b) for(int i=a; i<b; i++)
#define FD(i, a, b) for(int i=a; i>=b; i--)
#define REP(i, n) for(int i=0; i<n; i++)
#define CLR(a, b) memset(a, b, sizeof(a))
#define debug puts("**debug**")
#define LL long long
#define PB push_back
using namespace std;

const int maxn = 510;
int pref[maxn][maxn], order[maxn][maxn], next[maxn];
int hus[maxn], wife[maxn];
queue<int> q;

void enage(int man, int woman)
{
    int m = hus[woman];
    if(m)
    {
        wife[m] = 0;
        q.push(m);
    }
    wife[man] = woman;
    hus[woman] = man;
}

map<string, int> wo, ma;
map<int, string> ans1, ans2;
int man_cnt, woman_cnt, n;
int man_id(string a)
{
    if(!ma.count(a)) ma[a] = man_cnt++, ans1[man_cnt-1] = a;
    return ma[a];
}
int woman_id(string a)
{
    if(!wo.count(a)) wo[a] = woman_cnt++, ans2[woman_cnt-1] = a;
    return wo[a];
}

int main()
{
    while(~scanf("%d", &n))
    {
        man_cnt = woman_cnt = 1;
        wo.clear(), ma.clear(), ans1.clear(), ans2.clear();
        char a[111];
        int x, y;
        FF(i, 1, n+1)
        {
            scanf("%s", a); x = man_id(string(a));
            FF(j, 1, n+1)
            {
                scanf("%s", a); y = woman_id(string(a));
                pref[x][j] = y;
            }
            next[i] = 1;
            wife[i] = 0;
            q.push(i);
        }
        FF(i, 1, n+1)
        {
            scanf("%s", a); x = woman_id(string(a));
            FF(j, 1, n+1)
            {
                scanf("%s", a); y = man_id(string(a));
                order[x][y] = j;
            }
            hus[i] = 0;
        }
        while(!q.empty())
        {
            int man = q.front(); q.pop();
            int woman = pref[man][next[man]++];
            if(!hus[woman]) enage(man, woman);
            else if(order[woman][man] < order[woman][hus[woman]]) enage(man, woman);
            else q.push(man);
        }
        FF(i, 1, n+1) cout<<ans1[i]<<" "<<ans2[wife[i]]<<endl;
        puts("");
        while(!q.empty()) q.pop();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值