题意:给一个数字n。输入n串字符。你需要给出一串字符x,可以把n串字符分为两份。一份<=x 一份 > x。首先考虑x最短,其次考虑字典序最小。
思路:最先可以想到的是,把字符串排序,找到最中间的两串。接下来比较麻烦的是如何通过比较两串得到x。
设s1, s2为中间的两串字符串且s1 < s2。采用逐个字符比较需要注意以下情况:
一:比较的字符是否是s1串的最后一个。
二:比较的字符是否差别是大于一且比较字符为s2的最后一个字符:如s1 = ABCC ,s2 = ABD。那么x只能为ABCC。若s1 = ABCC, s2 = ABE。那么x = ABD。
三:小心Z: 如s1 = ABZZ , s2 = AB。那么s1 = ABZZ。而不是AB(Z +1)。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1000 + 5;
int main()
{
string str[maxn];
int n;
while(scanf("%d", &n) == 1 && n)
{
for(int i = 0; i < n; i++)
cin>>str[i];
sort(str, str + n);
int p = n / 2 - 1;
string s1 = str[p], s2 = str[p + 1], ans;
for(int i = 0; i < s1.size(); i++)//两个字符串不同的情况一定在到达s2末端前显现出来。
{
if(s1[i] == s2[i])
ans = ans + s1[i];
else
{
if(i == s1.size() - 1) ans += s1[i];
else if(s2[i] - s1[i] > 1 || i != s2.size() - 1) ans = ans + char(s1[i] + 1);
else
{
ans = ans + s1[i];
for(int j = i + 1; j < s1.size(); j++)
{
if(j == s1.size() - 1) {ans = ans + s1[j]; break;}
else if(s1[j] != 'Z') {ans = ans + char(s1[j] + 1); break;}
else ans = ans +'Z';
}
}
break;
}
}
cout<<ans<<endl;
}
return 0;
}