Marriage is Stable(HDOJ 1522)
Problem Description
Albert, Brad, Chuck are happy bachelors who are in love with Laura, Marcy, Nancy. They all have three choices. But in fact, they do have some preference in mind. Say Albert, he likes Laura best, but that doesn't necesarily mean Laura likes him. Laura likes Chuck more than Albert. So if Albert can't marry Laura, he thinks Nancy a sensible choice. For Albert, he orders the girls Laura > Nancy > Marcy.
For the boys:
Albert: Laura > Nancy > Marcy
Brad: Marcy > Nancy > Laura
Chuck: Laura > Marcy > Nancy
For the girls:
Laura: Chuck > Albert > Brad
Marcy: Albert > Chuck > Brad
Nancy: Brad > Albert > Chuck
But if they were matched randomly, such as
Albert <-> Laura
Brad <-> Marcy
Chuck <-> Nancy
they would soon discover it's not a nice solution. For Laura, she likes Chuck instead of Albert. And what's more, Chuck likes Laura better than Nancy. So Laura and Chuck are likely to come together, leaving poor Albert and Nancy.
Now it's your turn to find a stable marriage. A stable marriage means for any boy G and girl M, with their choice m[G] and m[M], it will not happen that rank(G, M) < rank(G, m[G])and rank(M, G) < rank(M, m[M]).
Input
Each case starts with an integer n (1 <= n <= 500), the number of matches to make.
The following n lines contain n + 1 names each, the first being name of the boy, and rest being the rank of the girls.
The following n lines are the same information for the girls.
Process to the end of file.
Output
If there is a stable marriage, print n lines with two names on each line. You can choose any one if there are multiple solution. Print "Impossible" otherwise.
Print a blank line after each test.
3 Albert Laura Nancy Marcy Brad Marcy Nancy Laura Chuck Laura Marcy Nancy Laura Chuck Albert Brad Marcy Albert Chuck Brad Nancy Brad Albert Chuck
Sample Output
Albert Nancy Brad Marcy Chuck Laura
My Code
这题是稳定婚姻问题的模板,一般采用 Gale-Shapley算法。采用贪心的方法,每个男生表白自己没有表白过的女生中最喜欢的那个,如果那个女生没有对象,你们就匹配成功,如果有对象,但那个女生更喜欢你,那么也匹配成功,而那个被甩的男生恢复单身。这样不断循环,直到所有人都有对象。理论上应该是不会出现有人没对象的情况,所以这里这里不考虑 "Impossible" 也能过。
#include
#include
#include
#include
#include