poj3487 稳定婚姻匹配

稳定婚姻匹配可参考Matrix67的博客http://www.matrix67.com/blog

另外可参考Richard A.Brualdi的《组合数学》

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<string.h>
 4 #include<stack>
 5 using namespace std;
 6 const int maxn=200;
 7 int T,n,wp[maxn][maxn],wm[maxn],mm[maxn];
 8 
 9 int tran(char s)
10 {
11     int d=s;
12     return d;
13 }
14 int main()
15 {
16     //freopen("test.txt","r",stdin);
17     scanf("%d",&T);
18     while(T--)
19     {
20         scanf("%d",&n);
21         int i,j;
22         char c[2];
23         memset(mm,0,sizeof(mm));
24         memset(wm,0,sizeof(wm));
25         for(i=0;i<n;i++)
26         {
27             scanf("%s",c);
28             mm[tran(c[0])]=-1;
29         }
30         for(i=0;i<n;i++)
31         {
32             scanf("%s",c);
33             wm[tran(c[0])]=-1;
34         }
35         char s[maxn];
36         stack<int> mp[maxn];
37         for(i=0;i<n;i++)
38         {
39             scanf("%s",s);
40             int len=strlen(s);
41             int a=tran(s[0]);
42             for(j=len-1;j>=2;j--)
43             {
44                 mp[a].push(tran(s[j]));
45             }
46         }
47         for(i=0;i<n;i++)
48         {
49             scanf("%s",s);
50             int len=strlen(s);
51             int a=tran(s[0]);
52             for(j=2;j<len;j++)
53             {
54                 wp[tran(s[j])][a]=j-1;
55             }
56         }
57         int bg='a',ed='z';
58         for(i=0;i<n*2;i++)
59         {
60             for(j=bg;j<=ed;j++)
61             {
62                 if(mm[j]==-1)
63                 {
64                     if(mp[j].empty())
65                     break;
66                     int cur=mp[j].top();
67                     if(wm[cur]==-1)
68                     {
69                         mm[j]=cur,wm[cur]=j;
70                     }
71                     else
72                     {
73                         int b=wm[cur];
74                         if(wp[j][cur]<wp[b][cur])
75                         {
76                             mm[j]=cur,wm[cur]=j;
77                             mm[b]=-1;
78                         }
79                     }
80                     mp[j].pop();
81                 }
82             }
83         }
84         for(i=bg;i<=ed;i++)
85         {
86             if(mm[i]!=0&&mm[i]!=-1)
87             printf("%c %c
",i,mm[i]);
88         }
89         if(T!=0)
90         printf("
");
91     }
92     return 0;
93 }
View Code
原文地址:https://www.cnblogs.com/longlongagocsu/p/3182158.html