UVALive 3989 - Ladies' Choice(稳定婚姻匹配)

题目链接:
UVALive 3989 - Ladies’ Choice
题意:
有n对男女,先给出每个女生对n位男生的选择意向,排在前面的优先选择,然后给出n位男生的选择意向,排在前面的优先选择.
输出每位女生的匹配,使得每位女生都是稳定的最佳选择.

/*
下面算法中存储女生的选择意向时有两种选择:队列和数组.把注释部分去掉//即是队列写法.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <queue>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 1010;

int T, n;
int x[MAX_N][MAX_N], y[MAX_N][MAX_N]; //x means girls, y means boys
//x[i][j] = k means ith girl's kth preference is jth boy
int matchx[MAX_N], matchy[MAX_N];
//matchx[i] is used to store ith girl's final match
int order[MAX_N];
//order[i] means the ith girl's choose order; initialized as 1
queue<int> girl[MAX_N]; // girl[i] is used to store ith girl's preference order

void GaleShapley()
{
    memset(matchy, -1, sizeof(matchy)); // all boy' states are initialized as -1 to imply not match
    queue<int> single; //store all single girls' index
    for(int i = 1; i <= n; i++) { single.push(i); } 
    while(!single.empty()){
        int tmpx = single.front(); //single girl
        single.pop();
        //int tmpy = girl[tmpx].front(); // tmpx's current priority preference
        //girl[tmpx].pop(); 
        int tmpy = x[tmpx][order[tmpx]++];
        int cur = matchy[tmpy]; //The boy tmpy's current match
        if(cur == -1) {
            matchx[tmpx] = tmpy;
            matchy[tmpy] = tmpx;
        }else if(y[tmpy][tmpx] < y[tmpy][cur]){ //The girl tmpx's preference is priority to the girl cur
            matchx[tmpx] = tmpy;
            matchy[tmpy] = tmpx;
            single.push(cur);
        }else {
            single.push(tmpx); //The girl tmpx doen't find match
        }
    }
}

int main()
{
    IOS;
    cin >> T;
    while(T-- > 0){
        cin >> n;
        for(int i = 1; i <= n; i++) { order[i] = 1; }
        for(int i = 1; i <= n; i++){
            //while(!girl[i].empty()) { girl[i].pop(); }
            for(int j = 1; j <= n; j++){
                cin >> x[i][j];
                //int t; 
                //cin >> t;
                //girl[i].push(t);
            }
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){
                int t;
                cin >> t;
                y[i][t] = j;
            }
        }
        GaleShapley();
        for(int i = 1; i <= n; i++){ //输出每位女生的匹配结果
            cout << matchx[i] << endl;
        }
        if(T > 0) cout << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值