1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <bits/stdc++.h> using namespace std; typedef pair<string, string> pss; bool st[200][10]; vector<pss> ans;
void Push(int x, char ch1, int y, char ch2) { string a = "ab", b = "ab"; a[0] = x + '0', a[1] = ch1; b[0] = y + '0', b[1] = ch2; ans.push_back({a, b}); st[ch1][x] = 1, st[ch2][y] = 1; }
void solve() { ans.clear(); memset(st, 0, sizeof(st)); int n; cin >> n; char ch; cin >> ch; map<char, vector<int>> mp; for(int i = 0; i < n * 2; i++) { string s; cin >> s; mp[s[1]].push_back(s[0] - '0'); } for(auto& [k, v] : mp) { sort(v.begin(), v.end()); } int i = 0, j = mp[ch].size() - 1; int t = mp[ch].size(); while(t > n) { auto p = mp[ch]; if(p[i] == p[j]){ cout << "IMPOSSIBLE\n"; return; } t -= 2; Push(p[i], ch, p[j], ch); i++, j--; } int x = n - ans.size() - t; for(auto& [k, v] : mp) { if(x == 0) break; if(k == ch) continue; for(int i = 0, j = v.size() - 1; i < j && v[i] < v[j] && x; i++, j--){ Push(v[i], k, v[j], k); x--; } } if(x){ cout << "IMPOSSIBLE\n"; return; } int p = ans.size(); for(auto x : mp[ch]) { if(!st[ch][x]) { Push(0, 'a', x, ch); } } for(auto& [k, v] : mp) { if(k == ch) continue; for(int i = 0; i < v.size(); i++){ if(!st[k][v[i]]){ string a = "ab"; a[0] = v[i] + '0', a[1] = k; ans[p++].first = a; } } } for(pss p : ans){ cout << p.first << ' ' << p.second << '\n'; } }
int main() { int t; cin >> t; while(t--) solve(); return 0; }
|