概述
算法分析课程作业(仅供参考)
源代码:
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:UsersAdministrator.jdkstemurin-11.0.12-1binjava.exe "-javaagent:E:IntelliJ IDEA 2020.1libidea_rt.jar=56703:E:IntelliJ IDEA 2020.1bin" -Dfile.encoding=UTF-8 -classpath D:JavaProjectJustForTestoutproductionJustForTest GaleShapley
0号男性---0号女性
1号男性---1号女性
2号男性---2号女性
Process finished with exit code 0
最后
以上就是俏皮火龙果为你收集整理的配对算法(Gale-Shapley)实现算法分析课程作业(仅供参考)的全部内容,希望文章能够帮你解决配对算法(Gale-Shapley)实现算法分析课程作业(仅供参考)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复