Stable Marrige
算法第一次作业!!
part1:暴力求解,遍历所有可能组合,输出一对stable的
part2:普通的通过preferences list求解
part3:第二问基础上加上cost
其实第一问好像跑不出来的,时间复杂度无穷大(捂脸),不过后来我知道了用全排列搞出所有组合
package pro;
/**
* Class to implement Stable Matching algorithms
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class Assignment1 {
// Part1: Implement a Brute Force Solution
public static ArrayList<Integer> stableMatchBruteForce(Preferences preferences) {
ArrayList<ArrayList<Integer>> prof_list=preferences.getProfessors_preference();
ArrayList<ArrayList<Integer>> stu_list=preferences.getStudents_preference();
int prof_length=preferences.getProfessors_preference().size();
int stu_length=preferences.getStudents_preference().size();
//random arraylist
ArrayList<Integer> p_match=randomMatching(prof_length);
ArrayList<Integer> s_match=new ArrayList<Integer>();
for(int i=0;i<prof_length;i++) {
s_match.add(p_match.indexOf(i));
}
if(ifStable(p_match,s_match,preferences)) {
p_match=randomMatching(prof_length);
s_match=new ArrayList<Integer>();
for(int i=0;i<prof_length;i++) {
s_match.add(p_match.indexOf(i));
}
}
return p_match;//prof opt
}
// Part2: Implement Gale-Shapley Algorithm,
public static ArrayList<Integer> stableMatchGaleShapley(Preferences preferences) {
ArrayList<ArrayList<Integer>> prof_list=preferences.getProfessors_preference();
ArrayList<ArrayList<Integer>> stu_list=preferences.getStudents_preference();
int prof_length=preferences.getProfessors_preference().size();
int stu_length=preferences.getStudents_preference().size();
//save the status of whether they`re matched,and initialize
ArrayList<Integer> prof_match=new ArrayList<Integer>();
ArrayList<Integer> stu_match=new ArrayList<Integer>();
for(int i=0;i<prof_length;i++) {
prof_match.add(-1);
stu_match.add(-1);
}
Queue<Integer> q=new LinkedList();
for(int i=0;i<prof_length;i++) {
q.offer(i);//insert element in the end, position 0 saves professor 1
}
//traverse prof,until empty
Integer prof_num=0;
while((prof_num=q.poll())!=nul