1. 程式人生 > >HDU 1522 Marriage is Stable 【穩定婚姻匹配】(模板題)

HDU 1522 Marriage is Stable 【穩定婚姻匹配】(模板題)

out while 模板 efi with false -c 講解 names

<題目鏈接>

題目大意:

給你N個男生和N個女生,並且給出所有男生和女生對其它所有異性的喜歡程度,喜歡程度越高的兩個異性越容易配對,現在求出它們之間的穩定匹配。

解題分析:

穩定婚姻問題的模板題,需要用到Gale_Shapley算法,GS算法講解 >>>

這個算法還是很直觀的。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <stack>
 4 #include <string>
 5 #include <map>
 6
#include <algorithm> 7 using namespace std; 8 9 #define N 505 10 #define clr(a,b) memset(a,b,sizeof(a)) 11 #define rep(i,s,t) for(int i=s;i<=t;i++) 12 13 int n,getmp_boy[N][N],getmp_girl[N][N],boy[N],girl[N],rnk[N]; 14 map<string,int>mp_boy,mp_girl; 15 string s,name_boy[N],name_girl[N];
16 17 void Gale_Shapley(){ 18 clr(boy,0);clr(girl,0); 19 rep(i,1,n) rnk[i]=1; 20 while(true){ 21 bool flag=false; 22 rep(i,1,n){ 23 if(!boy[i]){ 24 int x=getmp_boy[i][rnk[i]++]; //x為當前男生所最求的他沒有嘗試最求過的最喜歡的女生 25 if(!girl[x]){ //
如果這個女生沒有和男生配對 26 boy[i]=x; //那麽這對男女進行配對 27 girl[x]=i; 28 }else if(getmp_girl[x][i] > getmp_girl[x][girl[x]]){ //如果當前女生已經配對,那麽就判斷她對這兩個男生的喜歡程度 29 boy[girl[x]]=0; //將原來的男生拋棄 30 girl[x]=i; //將這兩個男女進行配對 31 boy[i]=x; 32 } 33 flag=true; 34 } 35 } 36 if(!flag)break; //如果所有男生都已配對,則直接退出 37 } 38 rep(i,1,n) cout<<name_boy[i]<<" "<<name_girl[boy[i]]<<endl; 39 } 40 41 int main(){ 42 ios_base::sync_with_stdio(false); 43 cin.tie(0);cout.tie(0); 44 while(cin>>n){ 45 mp_boy.clear();mp_girl.clear(); 46 int pos=1,tmp; 47 rep(i,1,n){ 48 cin>>s;name_boy[i]=s; 49 mp_boy[s]=i; 50 rep(j,1,n){ 51 cin>>s;tmp=mp_girl[s]; 52 if(!tmp){ //對於之前沒有出現過個的女生姓名,重新分配序號 53 tmp=pos++; 54 mp_girl[s]=tmp; 55 name_girl[tmp]=s; 56 } 57 getmp_boy[i][j]=tmp; //記錄第i個男生第j個喜歡的女生是tmp 58 } 59 } 60 rep(i,1,n){ 61 cin>>s;int x=mp_girl[s]; 62 rep(j,1,n){ 63 cin>>s;int y=mp_boy[s]; 64 getmp_girl[x][y]=n-j; //記錄第i個女生喜歡男生y的程度是n-j 65 } 66 } 67 Gale_Shapley(); 68 } 69 }

2019-01-17

HDU 1522 Marriage is Stable 【穩定婚姻匹配】(模板題)