Va 1175-Ladies 'choice (stable marital problem)

Source: Internet
Author: User
Va 1175-Ladies 'choice

Question Link

Given n men and N women, each person has a ranking of the opposite sex. From left to right, they like most to dislike most. Then, a stable match is required, so that N men and women do not have men who are more emotional than other women and women who are more emotional than other men

Idea: The algorithm process for stable marriage is as follows:
A man keeps proposing proposal, from the favorite to the least. Every time a woman chooses a favorite pairing among the propose, the current pairing is discarded, this process can be used to store the proposal man in a queue, so that the matching is completed until the queue is empty.

Code:

#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;const int N = 1005;int t, n;struct People {int order[N], now, match;} man[N], woman[N];queue<int> Q;bool gao(int u, int v) {if (woman[v].match == -1) {woman[v].match = u;return true;} else if (woman[v].order[woman[v].match] > woman[v].order[u]) {man[woman[v].match].now++;Q.push(woman[v].match);woman[v].match = u;return true;}return false;}int main() {scanf("%d", &t);while (t--) {scanf("%d", &n);for (int i = 0; i < n; i++) {man[i].now = 0;for (int j = 0; j < n; j++) {scanf("%d", &man[i].order[j]);man[i].order[j]--;}Q.push(i);}for (int i = 0; i < n; i++) {woman[i].match = -1;int tmp;for (int j = 0; j < n; j++) {scanf("%d", &tmp);tmp--;woman[i].order[tmp] = j;}}while (!Q.empty()) {int u = Q.front();Q.pop();int v = man[u].order[man[u].now];if (!gao(u, v)) {man[u].now++;Q.push(u);}}for (int i = 0; i < n; i++)man[woman[i].match].match = i;for (int i = 0; i < n; i++)printf("%d\n", man[i].match + 1);if (t) printf("\n");}return 0;}


Va 1175-Ladies 'choice (stable marital problem)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.