男女完全匹配算法

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
#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 << "男" << "\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;
}

  

  

posted @   天下岂有长生不灭者  阅读(403)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示