当前位置: 代码迷 >> 综合 >> UVALive 3989 - Ladies' Choice(稳定婚姻匹配)
  详细解决方案

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

热度:62   发布时间:2023-12-08 10:50:44.0

题目链接:
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 ordervoid GaleShapley()
{memset(matchy, -1, sizeof(matchy)); // all boy' states are initialized as -1 to imply not matchqueue<int> single; //store all single girls' indexfor(int i = 1; i <= n; i++) { single.push(i); } while(!single.empty()){int tmpx = single.front(); //single girlsingle.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 matchif(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 curmatchx[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;
}
  相关解决方案