# 稳定的婚姻问题幸福系数

3

1 2 3

2 3 1

1 2 3

1 2 3

2 3 1

3 1 2

16

3 2 1

``````#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

void stable_marriage(vector<vector<int>> &matrix) {
int n = matrix[0].size(), happiness_sum = 0;
vector<int> status(n * 2, -1);
queue<int> Q;
for (int i = 0; i < n; i++)
Q.push(i);

while (!Q.empty()) {
int i = Q.front();
Q.pop();
for (int j = 0; j < n; j++) {
if (status[matrix[i][j]] == -1) {
status[i] = matrix[i][j];
status[matrix[i][j]] = i;
break;
}
else {
int rank_1, rank_2;
for (int k = 0; k < n; k++) {
if (matrix[matrix[i][j]][k] == status[matrix[i][j]])
rank_1 = k;
if (matrix[matrix[i][j]][k] == i)
rank_2 = k;
}
if (rank_2 < rank_1) {
status[i] = matrix[i][j];
int old = status[matrix[i][j]];
status[old] = -1;
Q.push(old);
status[matrix[i][j]] = i;
break;
}
}
}
}
cout << happiness_sum << endl;
for (int i = n - 1; i >= 0; i--) {
cout << status[i] << ' ';
}
}
int main() {

//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);

int n;
cin >> n;
vector<vector<int>> matrix(n * 2, vector<int>(n));
for (int i = 0; i < n * 2; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

stable_marriage(matrix);
return 0;
}
``````