来一发模板题。。。貌似不存在无解情况。。。
#include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<fstream> #include<sstream> #include<bitset> #include<vector> #include<string> #include<cstdio> #include<cmath> #include<stack> #include<queue> #include<stack> #include<map> #include<set> #define FF(i, a, b) for(int i=a; i<b; i++) #define FD(i, a, b) for(int i=a; i>=b; i--) #define REP(i, n) for(int i=0; i<n; i++) #define CLR(a, b) memset(a, b, sizeof(a)) #define debug puts("**debug**") #define LL long long #define PB push_back using namespace std; const int maxn = 510; int pref[maxn][maxn], order[maxn][maxn], next[maxn]; int hus[maxn], wife[maxn]; queue<int> q; void enage(int man, int woman) { int m = hus[woman]; if(m) { wife[m] = 0; q.push(m); } wife[man] = woman; hus[woman] = man; } map<string, int> wo, ma; map<int, string> ans1, ans2; int man_cnt, woman_cnt, n; int man_id(string a) { if(!ma.count(a)) ma[a] = man_cnt++, ans1[man_cnt-1] = a; return ma[a]; } int woman_id(string a) { if(!wo.count(a)) wo[a] = woman_cnt++, ans2[woman_cnt-1] = a; return wo[a]; } int main() { while(~scanf("%d", &n)) { man_cnt = woman_cnt = 1; wo.clear(), ma.clear(), ans1.clear(), ans2.clear(); char a[111]; int x, y; FF(i, 1, n+1) { scanf("%s", a); x = man_id(string(a)); FF(j, 1, n+1) { scanf("%s", a); y = woman_id(string(a)); pref[x][j] = y; } next[i] = 1; wife[i] = 0; q.push(i); } FF(i, 1, n+1) { scanf("%s", a); x = woman_id(string(a)); FF(j, 1, n+1) { scanf("%s", a); y = man_id(string(a)); order[x][y] = j; } hus[i] = 0; } while(!q.empty()) { int man = q.front(); q.pop(); int woman = pref[man][next[man]++]; if(!hus[woman]) enage(man, woman); else if(order[woman][man] < order[woman][hus[woman]]) enage(man, woman); else q.push(man); } FF(i, 1, n+1) cout<<ans1[i]<<" "<<ans2[wife[i]]<<endl; puts(""); while(!q.empty()) q.pop(); } }