LightOJ 1400 Employment (Stable Marriage)
一道关于稳定婚姻的匹配题,算法的详细解释可以参考Matrix67的文章。
下面是我根据算法思路写出来的代码:
View Code
1 int comCan[N][N]; 2 int like[N], canLV[N][N]; 3 4 void input(int n) { 5 int x; 6 REP_1(i, n) { 7 REP_1(j, n) { 8 scanf("%d", &x); 9 comCan[i][j] = x - n; 10 } 11 } 12 REP_1(i, n) { 13 REP_1(j, n) { 14 scanf("%d", &x); 15 canLV[i][x] = j; 16 } 17 } 18 REP_1(i, n) like[i] = 1; 19 } 20 21 void work(int n) { 22 int mk[N]; 23 bool ok; 24 while (true) { 25 REP_1(i, n) mk[i] = 0; 26 REP_1(i, n) { 27 int can = comCan[i][like[i]]; 28 if (!mk[can]) mk[can] = i; 29 else { 30 if (canLV[can][i] < canLV[can][mk[can]]) mk[can] = i; 31 } 32 } 33 ok = true; 34 REP_1(i, n) if (!mk[i]) { 35 ok = false; 36 break; 37 } 38 if (ok) break; 39 REP_1(i, n) { 40 int can = comCan[i][like[i]]; 41 if (mk[can] != i) like[i]++; 42 } 43 } 44 } 45 46 void output(int c, int n) { 47 printf("Case %d:", c); 48 REP_1(i, n) printf(" (%d %d)", i, comCan[i][like[i]] + n); 49 puts(""); 50 } 51 52 int main() { 53 int T, n, CAS = 0; 54 scanf("%d", &T); 55 while (T-- && ~scanf("%d", &n)) { 56 input(n); 57 work(n); 58 output(++CAS, n); 59 } 60 return 0; 61 }
——written by Lyon