您的位置:首页 > 其它

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

2016-05-14 03:34 393 查看
题目链接:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: