Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : Stable Marriage Problem
Source : Codechef
Category : Data Structure
Algorithm : Stable Marriage Problem
Verdict : Accepted
- #include "bits/stdc++.h"
-
- #define ll long long int
- #define memo(a, b) memset(a, b, sizeof a)
-
- static const int maxn = 500 * 5;
-
- int prefer[maxn][maxn], N, wPartner[maxn], mFree[maxn];
-
- bool wPreferM1OverM(int w, int m1, int m)
- {
- for (int i = 1; i <= N; i++)
- {
- if (prefer[w][i] == m1) return true;
- if (prefer[w][i] == m) return false;
- }
- }
-
- void Stable_Marriage()
- {
- memo(wPartner, -1);
- memo(mFree, 0);
- int freeCount = N;
- while (freeCount)
- {
- int m;
- for (m = 1; m <= N; m++)
- {
- if (mFree[m] == 0) break;
- }
- for (int i = 1; i <= N && mFree[m] == 0; i++)
- {
- int w = prefer[m][i];
- if (wPartner[w] == -1)
- {
- wPartner[w] = m;
- mFree[m] = 1;
- freeCount--;
- }
- else
- {
- int m1 = wPartner[w];
- if (wPreferM1OverM(w, m1, m) == false)
- {
- wPartner[w] = m;
- mFree[m] = 1;
- mFree[m1] = 0;
- }
- }
- }
- }
- int woman[maxn];
- for (int i = N; i <= 2 * N; i++)
- {
- woman[wPartner[i]] = i - N;
- }
- for (int i = 1; i <= N; i++)
- {
- printf("%d %d\n", i, woman[i]);
- }
- }
-
- int main()
- {
- int tc;
- scanf("%d", &tc);
- for (int tcase = 1; tcase <= tc; tcase++)
- {
- scanf("%d", &N);
-
- for (int i = 1; i <= N; i++)
- {
- int w;
- scanf("%d", &w);
- w += N;
- for (int j = 1; j <= N; j++)
- {
- scanf("%d", &prefer[w][j]);
- }
- }
-
- for (int i = 1; i <= N; i++)
- {
- int m;
- scanf("%d", &m);
- for (int j = 1; j <= N; j++)
- {
- int w;
- scanf("%d", &w);
- prefer[m][j] = w + N;
- }
- }
- Stable_Marriage();
- }
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.