#include<iostream> #include<String> #include"Free_W_M_Stack.cpp" using namespace std; int Number1(string elem, string A[], int n){//返回某个人的匹配号 for (int i = 0; i < n; i++){ if (elem == A[i]) return i; } return -1; } int main(){ int n;//n代表有多少对男女 cout << "请输出有多少对男女:"; cin >> n; W_M_Stack<int> M_Free(n);//建立一个男人的单身库 string * M_Name = new string[n], *W_Name = new string[n], temp; int **Man = new int*[n], **Woman = new int*[n];//前者代表每个男性的心中女性的排名,后者代表心中的男性的排名 int *W_IsDating=new int[n];//-1代表还没有约会过,大于-1的值是约会的对象 int *M_Love = new int[n];//每个男人目前心中预定的表白的人的排名 cout << "请输出男/女性名字从 0 到 " << n - 1 << " 的各个心目中女/男性编号 0 到 " << n - 1 << " 的排名(空格):" << endl; cout << "输出男性的名字 : " << endl; for (int i = 0; i < n; i++){ cin >> M_Name[i]; M_Free.push(i); Man[i] = new int[n]; cout << M_Name[i] << " 的女性排名是:"; for (int j = 0; j < n; j++){ cin >> temp; if (i == 0) W_Name[j] = temp; Man[i][j] = Number1(temp, W_Name, n); } M_Love[i] = 0; } cout << endl << endl << "输出女性的名字 : " << endl; for (int i = 0; i < n; i++){ Woman[i] = new int[n]; cout << W_Name[i] << " 的男性排名是:"; for (int j = 0; j < n; j++){ cin >> temp; int s=Number1(temp, M_Name, n); Woman[i][s] = j; } W_IsDating[i] = -1; } while (M_Free.isEmpty()!=-1){//若某个男人还是单身 int i = M_Free.pop(); if (W_IsDating[Man[i][M_Love[i]]] == -1){//若男人未表白的女性最赞赏的还未约会 W_IsDating[Man[i][M_Love[i]]] = i;//女人记录约会的对象 M_Love[i]++; } else{ int k = W_IsDating[Man[i][M_Love[i]]];//如果男人看上的女人已经开始约会了,k代表约会的对象的id if (Woman[Man[i][M_Love[i]]][k] <= Woman[Man[i][M_Love[i]]][i]){//如果女人处于约会状态而且目前的对象优于表白的男人 ++M_Love[i];//表白的男人开始找下一个 M_Free.push(i); } else{//如果女人处于约会状态而且对表白者的好感优于目前的约会对象 W_IsDating[Man[i][M_Love[i]]] = i; M_Free.push(k); ++M_Love[i];//表白成功的预定下一个最赞赏的女性 } } } cout << "最终生成的稳定匹配是:" << endl; cout << "男" << " " << "女" << " " << endl; for (int i = 0; i < n; i++){ cout << M_Name[i] << " " << W_Name[Man[i][--M_Love[i]]] << " " << endl; } for (int i = 0; i < n; i++){ delete[] Man[i]; delete[]Woman[i]; } delete[] W_Name; delete[] M_Name; delete[] W_IsDating; delete[] M_Love; }
#include<iostream> using namespace std; template<class T>class W_M_Stack{//记录男女的单身的情况栈 int Maxsize; int size = -1; T* st; public: W_M_Stack(int n){ Maxsize = n; st = new T[Maxsize]; } int isEmpty(){ if (size >= Maxsize) return 1; if (size == -1) return -1; return 0; } bool push(T elem){ if (isEmpty() != 1){ st[++size] = elem; return true; } return false; } T pop(){ if (isEmpty() != -1){ size--; return st[size + 1]; } return -1; } ~W_M_Stack(){ delete[] st; } };