稳定婚姻问题,虽然简单,但是挺有意思的。
poj3487中要注意,这道题中的字母并不是一定要从a开始连续的,注意哦。
#include<iostream> #include<algorithm> #include<fstream> #include<queue> using namespace std; char male[26]; char female[26]; int n; int T; int maleprefer[26][26]; int femaleprefer[26][26]; int fucked[26]; bool reject[26][26]; struct OUT { char ch1; char ch2; }output[26]; int cmp(const void *out1,const void *out2) { OUT *p1=(OUT *)out1; OUT *p2=(OUT *)out2; return int(p1->ch1 - p2->ch1); } int getWeight(int women,int man) { for(int i=0;i<n;i++) { if(femaleprefer[women][i]==man) return n- i; } } int getMale(char ch) { int index; for(index=0;index<n;index++) { if(male[index]==ch) return index; } return -1; } int getFemale(char ch) { int index; for(index=0;index<n;index++) { if(female[index]==ch) return index; } return -1; } int main() { freopen("input.txt","r",stdin); scanf("%d\n",&T); while(T--) { queue<int> myQueue; //input a case scanf("%d\n",&n); for(int i=0;i<n;i++) { scanf("%c ",&male[i]); myQueue.push(i); fucked[i]=-1; } for(int i=0;i<n;i++) { if(i<n-1) scanf("%c ",&female[i]); else scanf("%c\n",&female[i]); } for(int i=0;i<n;i++) { char now_man; scanf("%c",&now_man); int index=getMale(now_man); scanf("%c",&now_man); for(int j=0;j<n;j++) { char temp; scanf("%c",&temp); maleprefer[index][j]=getFemale(temp); reject[index][j]=false; } scanf("\n"); } for(int i=0;i<n;i++) { char now_woman; scanf("%c",&now_woman); int index=getFemale(now_woman); scanf("%c",&now_woman); for(int j=0;j<n;j++) { char temp; scanf("%c",&temp); femaleprefer[index][j]=getMale(temp); } scanf("\n"); } //end of input //marry while(myQueue.empty()==false) { int now_man=myQueue.front(); myQueue.pop(); for(int i=0;i<n;i++) { int now_women=maleprefer[now_man][i]; if(reject[now_man][now_women]==false) { if(fucked[now_women]==-1) { fucked[now_women]=now_man; break; } else if(fucked[now_women]>=0&&getWeight(now_women,now_man)>getWeight(now_women,fucked[now_women])) { reject[fucked[now_women]][now_women]=true; myQueue.push(fucked[now_women]); fucked[now_women]=now_man; break; } else { reject[now_man][now_women]=true; } } } } for(int i=0;i<n;i++) { output[i].ch1=male[fucked[i]]; output[i].ch2=female[i]; } qsort(output,n,sizeof(OUT),cmp); for(int i=0;i<n;i++) { cout<<output[i].ch1<<" "<<output[i].ch2<<endl; } cout<<endl; } return 0; }