Ladies' Choice
64-bit integer IO format: %lld Java class name: Main
Background
Teenagers from the local high school have asked you to help them with the organization of next years Prom. The idea is to find a suitable date for everyone in the class in a fair and civilized way. So, they have organized a web site where all students, boys and girls, state their preferences among the class members, by ordering all the possible candidates. Your mission is to keep everyone as happy as possible. Assume that there are equal numbers of boys and girls.
Problem
Given a set of preferences, set up the blind dates such that there are no other two people of opposite sex who would both rather have each other than their current partners. Since it was decided that the Prom was Ladies' Choice, we want to produce the best possible choice for the girls.
Input
Input consists of multiple test cases the first line of the input contains the number of test cases. There is a blank line before each dataset. The input for each dataset consists of a positive integer N, not greater than 1,000, indicating the number of couples in the class. Next, there are N lines, each one containing the all the integers from 1 to N, ordered according to the girls preferences. Next, there are N lines, each one containing all the integers from 1 to N, ordered according to the boys preferences.
Output
The output for each dataset consists of a sequence of N lines, where the i-th line contains the number of the boy assigned to the i-th girl (from 1 to N). Print a blank line between datasets.
Sample Input
1
5
1 2 3 5 4
5 2 4 3 1
3 5 1 2 4
3 4 2 1 5
4 5 1 2 3
2 5 4 1 3
3 2 4 1 5
1 2 4 3 5
4 1 2 5 3
5 3 2 4 1
Sample Output
1
2
5
3
4
Source
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1010; 4 int n,mr[maxn][maxn],miss[maxn][maxn]; 5 int wife[maxn],husband[maxn],nxt[maxn]; 6 queue<int>q; 7 void engage(int man,int woman) { 8 if(husband[woman]) { 9 wife[husband[woman]] = 0; 10 q.push(husband[woman]); 11 } 12 husband[woman] = man; 13 wife[man] = woman; 14 } 15 void GaleShapley() { 16 while(!q.empty()) { 17 int man = q.front(); 18 q.pop(); 19 int woman = mr[man][nxt[man]++]; 20 if(!husband[woman]) engage(man,woman); 21 else if(miss[woman][husband[woman]] > miss[woman][man]) 22 engage(man,woman); 23 else q.push(man); 24 } 25 } 26 int main() { 27 int kase,tmp; 28 scanf("%d",&kase); 29 while(kase--) { 30 scanf("%d",&n); 31 while(!q.empty()) q.pop(); 32 for(int i = 1; i <= n; ++i) { 33 for(int j = 1; j <= n; ++j) 34 scanf("%d",mr[i]+j); 35 nxt[i] = 1; 36 wife[i] = 0; 37 q.push(i); 38 } 39 for(int i = 1; i <= n; ++i) { 40 for(int j = 1; j <= n; ++j) { 41 scanf("%d",&tmp); 42 miss[i][tmp] = j; 43 } 44 husband[i] = 0; 45 } 46 GaleShapley(); 47 for(int i = 1; i <= n; ++i) 48 printf("%d ",wife[i]); 49 if(kase) putchar(' '); 50 } 51 return 0; 52 }