I really thought about this very complicated question. I was looking for the rules and formulas with scratch paper, and then there were always some special cases.
Then WA N times. In desperation, I read someone else's blog and was shocked. Direct brute force enumeration of two adjacent strings
All the possibilities in it are enough... It's really a miracle of violence!
#include<cstdio> #include<iostream> #include<algorithm> #include<string> #define REP(i, a, b) for(int i = (a); i < (b); i++) using namespace std; const int MAXN = 1123; string a[MAXN]; string work(string a, string b) { int pos = 0; string s0 = "", t; while(1) { REP(i, 0, 26) { t = s0; t += i + 'A'; if(a <= t && t < b) return t; } s0 += a[pos++]; } } intmain() { int n; while(scanf("%d", &n) && n) { REP(i, 0, n) cin >> a[i]; sort(a, a + n); int tmp = (n - 1) / 2; cout << work(a[tmp], a[tmp+1]) << endl; } return 0; }