稳定婚姻问题:有n位男士和n位女士,每一个人都对每个异性有一个喜好度的排序,代表对他的喜爱程度,现在希望给每个男士找一个女士作配偶,使得每人恰好有一个异性配偶。如果男士u和女士v不是配偶但喜欢对方的程度都大于喜欢各自当前配偶的程度,则称他们为一个不稳定对。稳定婚姻问题就是希望找出一个不包含不稳定对的方案。
import java.util.Arrays; import java.util.Scanner; public class stablemarry3487 { class boy { int stack[] = new int[27], top; int match; int get() { return stack[top++]; } } class girl { int rank[] = new int[27], id; int stack[] = new int[30], top; void insert(int k) { stack[top++] = k; } void match() { if (top ==0) return; //在所有向自己求婚的男生中选择最喜欢的一个 int min = 99, idx = -1; for (int i = 0; i < top; i++) if (rank[stack[i]] < min) { idx = stack[i]; min = rank[idx]; } // 将其他男生加入单身队列 for (int i = 0; i < top; i++) if (idx != stack[i]) queue[tail++] = stack[i]; //通知选择的男生匹配成功并保存到备选队列中 bb[idx].match = id; top = 1; stack[0]=idx; } } Scanner scan = new Scanner(System.in); int queue[] = new int[30], head, tail, n; boy bb[] = new boy[30]; girl gg[] = new girl[30]; void init() { n = scan.nextInt(); head = tail = 0; Arrays.fill(bb, null); Arrays.fill(gg, null); for (int i = 0; i < n; i++) { String s = scan.next(); queue[tail++] = s.charAt(0) - 'a'; } for (int i = 0; i < n; i++) scan.next(); for (int i = 1; i <= n; i++) { String s = scan.next(); int k = s.charAt(0) - 'a'; bb[k] = new boy(); for (int j = 0; j < n; j++) bb[k].stack[j] = s.charAt(j + 2) - 'A'; } for (int i = 0; i < n; i++) { String s = scan.next(); int k = s.charAt(0) - 'A'; gg[k] = new girl(); gg[k].id = k; for (int j = 0; j < n; j++) gg[k].rank[s.charAt(j + 2) - 'a'] = j; } } void work() { while (head != tail) { //单身男性向没有拒绝自己且最喜欢的女生求婚 for (int i = head; i < tail; i++) { int k = queue[i]; int p = bb[k].get(); gg[p].insert(k); } head = tail = 0; for (int i = 0; i < 26; i++) if (gg[i] != null) gg[i].match();//女生在想自己求婚的男生中选择最喜欢的并把其他的添加到队列中 } for (int i = 0; i < 26; i++) if (bb[i] != null) System.out.println((char) ('a' + i) + " " + (char) ('A' + bb[i].match)); } void run() { int cas = scan.nextInt(); while (cas-- > 0) { init(); work(); System.out.println(); } } public static void main(String[] args) { new stablemarry3487().run(); } }