男女完全匹配算法
#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代表約會的對象的idif (Woman[Man[i][M_Love[i]]][k] <= Woman[Man[i][M_Love[i]]][i]){//如果女人處于約會狀態(tài)而且目前的對象優(yōu)于表白的男人++M_Love[i];//表白的男人開始找下一個M_Free.push(i);}else{//如果女人處于約會狀態(tài)而且對表白者的好感優(yōu)于目前的約會對象W_IsDating[Man[i][M_Love[i]]] = i;M_Free.push(k);++M_Love[i];//表白成功的預定下一個最贊賞的女性}}}cout << "最終生成的穩(wěn)定匹配是:" << endl;cout << "男" << "\t" << "女" << "\t" << endl;for (int i = 0; i < n; i++){cout << M_Name[i] << "\t" << W_Name[Man[i][--M_Love[i]]] << "\t" << 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;} };
轉載于:https://www.cnblogs.com/1996313xjf/p/5895473.html
總結
- 上一篇: 昨天事情还是比较多,让我晚上加了会班
- 下一篇: 总是骗人的你