代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| #include<queue> #include <iostream> #define MAX 10
using namespace std;
int main(){ int hospital_num, student_num; int HospitalPref[MAX][MAX], StudentPref[MAX][MAX]; int HospitalInverse[MAX][MAX], StudentInverse[MAX][MAX]; int confernstudent[MAX], confernhospital[MAX]; int count[MAX]; queue<int> FreeHospitals; cout << "请输入医院或学生的总数:" << endl; cin >> hospital_num; student_num = hospital_num; for (int i = 0; i < hospital_num; i++){ cout << "请输入第" << i+1 << "个医院的喜好排序" << endl; FreeHospitals.push(i); for (int j = 0; j < student_num; j++){ cin >> HospitalPref[i][j]; HospitalPref[i][j]--; } } for (int i = 0; i < student_num; i++){ cout << "请输入第" << i+1 << "个学生的喜好排序" << endl; for (int j = 0; j < hospital_num; j++){ cin >> StudentPref[i][j]; StudentPref[i][j]--; } } for (int i = 0; i < hospital_num; i++){ for (int j = 0; j < student_num; j++){ HospitalInverse[i][HospitalPref[i][j]] = j; } } for (int i = 0; i < student_num; i++){ for (int j = 0; j < hospital_num; j++){ StudentInverse[i][StudentPref[i][j]] = j; } }
for (int i = 0; i < hospital_num; i++){ confernstudent[i] = -1; confernhospital[i] = -1; count[i] = 0; }
while(FreeHospitals.size() != 0){ int hospital = FreeHospitals.front(); for (int i = count[hospital]; i < student_num; count[hospital]++, i++){ if (confernstudent[HospitalPref[hospital][i]] == -1){ confernstudent[HospitalPref[hospital][i]] = hospital; confernhospital[hospital] = HospitalPref[hospital][i]; FreeHospitals.pop(); break; }
else if (StudentInverse[hospital] < StudentInverse[confernstudent[HospitalPref[hospital][i]]]){ FreeHospitals.push(confernstudent[HospitalPref[hospital][i]]); confernhospital[confernstudent[HospitalPref[hospital][i]]] = -1; confernstudent[HospitalPref[hospital][i]] = hospital; confernhospital[hospital] = HospitalPref[hospital][i]; FreeHospitals.pop(); break; }
else { } } }
for (int i = 0; i < hospital_num; i++){ cout << "医院" << i+1 << "-----学生" << confernhospital[i]+1 << endl; } }
|
总结:
稳定匹配算法的实现我采用的是c++语言。在程序中,将医院与学生的喜好和医院与学生实际的匹配结果分别建立了四个二维数组;定义了配对次数和一个表示未配对医院的线性表。
程序首先读取医院(学生)的总数,再依次读取每个医院和学生的喜好排序,然后初始化每个医院和学生的状态,并将每个医院提出配对的次数赋值成0。进入循环依次取出队列中的第一个医院, 医院按照自己的喜欢序列降序对学生提出配对直到医院被配对,如果这个学生未被配对,将医院学生配对,将该医院从队列删除,如果学生较之已配对医院更喜欢这个医院,则将原配对医院加入未配对医院队列且医院的状态设置成未配对。待FreeHospitals的队列为空时结束循环后输出匹配结果。
程序使用了线性表queue,相比于数组而言大大缩短了运行所需时间。然而,在这样的场景中G-S匹配并不是公平的,由于每次迭代按照M中递减偏好尝试匹配,它是一种偏向于M节点的算法。算法产出的稳态匹配结果,所有的学校都匹配了尽可能好好的结果,而所有学生都匹配了尽可能不好的结果。