算法分析课程作业(仅供参考)
源代码:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
/**
* @description: Gale-Shapley algorithm
* @author: Qing Zhang
* @time: 09
*/
public class GaleShapley {
/**
* @Description: GS algorithm
* note: The number of men must be equal to women.
* @Param: [
* paraManPreferences : Men's Descending Preference Array for Women.
* paraWomanPreferences : Women's Descending Preference Array for Men
* ]
* @return: java.util.HashMap<java.lang.Integer, java.lang.Integer>
*/
public static HashMap<Integer, Integer> gsAlgorithm(int[][] paraManPreferences, int[][] paraWomanPreferences) {
// initial.
int numOfMan = paraManPreferences.length; // number of men
int numOfWoman = paraWomanPreferences.length; // number of women
if (numOfMan != numOfWoman) {
System.out.println("The data format is wrong!");
return null;
}
// Record whether women are free
boolean[] singleWoman = new boolean[numOfWoman];
// Women’s preference for men, sorted by male number
int[][] womanPreferencesToMan = new int[numOfWoman][numOfMan];
for (int i = 0; i < numOfWoman; i++) {
for (int j = 0; j < numOfMan; j++) {
womanPreferencesToMan[i][paraWomanPreferences[i][j]] = j;
}
}
// Single man
Queue<Integer> singleMan = new LinkedList<>();
// Results after allocation (female, male)
HashMap<Integer, Integer> lovers = new HashMap<>();
for (int i = 0; i < numOfMan; i++) {
singleMan.add(i);
}
// Loop... Find the woman for every single man.
while (!singleMan.isEmpty()) {
int curMan = singleMan.peek();
int curWoman;
for (int i = 0; i < numOfWoman; i++) {
curWoman = paraManPreferences[curMan][i];
if (!singleWoman[curWoman]) {
lovers.put(curWoman, curMan);
singleWoman[curWoman] = true;
singleMan.poll();
break;
} else if (womanPreferencesToMan[curWoman][lovers.get(curWoman)]
> womanPreferencesToMan[curWoman][curMan]) {
singleMan.add(lovers.get(curWoman));
lovers.put(curWoman, curMan);
singleMan.poll();
break;
}
}
}
return lovers;
}
public static void main(String[] args) {
int[][] man = new int[][]{{0, 1, 2}, {1, 0, 2}, {0, 1, 2}};
int[][] woman = new int[][]{{1, 0, 2}, {0, 1, 2}, {0, 1, 2}};
HashMap<Integer, Integer> lovers = GaleShapley.gsAlgorithm(man, woman);
if (lovers != null) {
for (Map.Entry<Integer, Integer> entry : lovers.entrySet()) {
System.out.println(entry.getValue() + "号男性---" + entry.getKey() + "号女性");
}
}
}
}
构造数据:
运行结果:
C:\Users\Administrator\.jdks\temurin-11.0.12-1\bin\java.exe "-javaagent:E:\IntelliJ IDEA 2020.1\lib\idea_rt.jar=56703:E:\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaProject\JustForTest\out\production\JustForTest GaleShapley
0号男性---0号女性
1号男性---1号女性
2号男性---2号女性
Process finished with exit code 0