A classic question hardly needs to be modeled. Use hash to record the ID number and set the template to OK ~~~
The following code is used:
# Include <iostream>
# Include <queue>
Using namespace STD;
# Deprecision Max 1010
Long N;
Long mlove [Max] [Max];
Long wlove [Max] [Max];
Long couple [Max];
Long pare [Max];
Queue <long> sq;
Void gale_shapley ()
{
Long I, man, woman;
While (! Sq. Empty ())
Sq. Pop ();
Memset (couple,-1, sizeof (couple ));
For (I = 1; I <= N; I ++)
Sq. Push (I );
While (! Sq. Empty ())
{
Man = SQ. Front ();
Sq. Pop ();
For (I = 1; I <= N; I ++)
{
If (mlove [Man] [I]! =-1)
{
// Select a girl that is not rejected and most popular
Woman = mlove [Man] [I];
Mlove [Man] [I] =-1;
Long pre = Couple [Woman];
If (pre =-1)
{
Couple [Woman] = man;
Pare [Man] = woman;
Break;
}
Else
{
If (wlove [Woman] [Man]> wlove [Woman] [pre])
{
Sq. Push (pre );
Couple [Woman] = man;
Pare [Man] = woman;
Break;
}
}
}
}
}
}
Long hash [256];
Char m_rev [256];
Char w_rev. [256];
Char STR [1000];
Int main ()
{
Long I, j, T;
Scanf ("% lD", & T );
Long B = 1;
While (t --)
{
If (B = 1)
{
+ + B;
}
Else
{
Puts ("");
}
Scanf ("% lD", & N );
Memset (hash, 0, sizeof (hash ));
Getchar ();
For (I = 1; I <= N; ++ I)
{
Char ch;
Scanf ("% C", & Ch );
Hash [CH] = I;
M_rev [I] = CH;
}
For (I = 1; I <= N; ++ I)
{
Char ch;
Scanf ("% C", & Ch );
Hash [CH] = I;
W_rev [I] = CH;
}
For (I = 1; I <= N; I ++)
{
Char ch;
Scanf ("% C: % s", & Ch, STR );
Getchar ();
For (j = 1; j <= N; j ++)
{
Mlove [hash [CH] [J] = hash [STR [J-1]; // record the number of the person you like
}
}
For (I = 1; I <= N; I ++)
{
Char ch;
Scanf ("% C: % s", & Ch, STR );
Getchar ();
For (j = 1; j <= N; j ++)
{
Wlove [hash [CH] [hash [STR [J-1] = N-J; // record liking from large to small
}
}
Gale_shapley ();
For (I = 'a'; I <= 'Z'; I ++)
{
If (hash [I])
{
Printf ("% C \ n", I, w_rev [pare [hash [I]); // for the spouse of a male
}
}
}
Return 0;
}