Stable marriage template (from HDU)

Source: Internet
Author: User

Stable marriage is a type of bipartite matching.

The following code has been fixed to fix several variables in the original template:

 

 

# Include <iostream>
# Include <queue>
Using namespace STD;

# Deprecision Max 1010

Int N;
Int mlove [Max] [Max];
Int wlove [Max] [Max];
Int couple [Max];
Int pare [Max];

Queue <int> sq;
Void gale_shapley ()
{
Int 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) // if a boy has not selected this girl
{
// Select a girl that is not rejected and most popular
Woman = mlove [Man] [I]; // select your favorite girl
Mlove [Man] [I] =-1; // select and Mark
Long pre = Couple [Woman];
If (pre =-1) // if no girl is paired
{
Couple [Woman] = man; // match
Pare [Man] = woman; // match
Break;
}
Else // if paired
{
If (wlove [Woman] [Man]> wlove [Woman] [pre]) // if a girl prefers this boy more
{
Sq. Push (pre); // put the current data in the queue
Couple [Woman] = man; // match
Pare [Man] = woman; // match
Break;
}
}
}
}
}/While
}

Int main ()
{
Int I, j, T, HJ;
Scanf ("% d", & T );
While (t --)
{
Scanf ("% d", & N );
For (I = 1; I <= N; I ++)
{
For (j = 1; j <= N; j ++)
{
Scanf ("% d", & mlove [I] [J]); // record the number of the person you like
}
}
For (I = 1; I <= N; I ++)
{
For (j = 1; j <= N; j ++)
{
Scanf ("% d", & HJ );
Wlove [I] [HJ] = N-J; // The degree of liking for a record ranges from large to small.
}
}

Gale_shapley ();

For (I = 1; I <= N; I ++)
Printf ("% d \ n", pare [I]); // For the spouse of the male
}
Return 0;
}

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.