※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 9002번 문제인 Match Maker이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/9002 

 

9002번: Match Maker

Print exactly one line for each test case . The line should contain a stable match for the test case. Each match should be represented as a sequence of the women’s id, according to the increasing order of men ’s id. The woman with the first id in the

www.acmicpc.net

주어진 문제는 Stable Marriage Problem(Stable Matching Problem; 이하 SMP)과 같다. SMP를 O(N^2)에 해결하는 알고리즘으로 Gale-Shapley 알고리즘이 잘 알려져있다.

 

테스트케이스별로 기존에 사용한 배열 등을 초기화하는 것을 잊지 말고 잘 구현하여 문제를 해결하자.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

int MtoF[101][101];
int FtoM[101][101];
int iter[101];
int matching[101]; // F가 matching된 사람

int ans[101];

void solve() {
	memset(iter, 0, sizeof(iter));
	memset(matching, 0, sizeof(matching));

	int N; cin >> N;
	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= N; j++) {
			int x; cin >> x;
			MtoF[i][j] = x;
		}
	}

	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= N; j++) {
			int x; cin >> x;
			FtoM[i][x] = j;
		}
	}

	queue<int> que;
	for (int i = 1; i <= N; i++) {
		que.push(i);
	}

	while (!que.empty()) {
		int curM = que.front(); que.pop();
		int curF = MtoF[curM][++iter[curM]];
		if (matching[curF] == 0) matching[curF] = curM;
		else if (FtoM[curF][curM] < FtoM[curF][matching[curF]]) {
			que.push(matching[curF]);
			matching[curF] = curM;
		}
		else que.push(curM);
	}

	for (int i = 1; i <= N; i++) {
		ans[matching[i]] = i;
	}

	for (int i = 1; i <= N; i++) cout << ans[i] << ' ';
	cout << '\n';
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int T; cin >> T;

	while (T--) {
		solve();
	}
}
728x90

+ Recent posts