原题链接: UVa-1610
题目大意:
输入一个n个(偶数个)字符串的集合D,输出一个字符串S,使得S尽量短的前提下满足大于等于一半的D,小于另一半的D。
参考博客:
解题思路:
整体思路很简单,先排序,找出中间的两个字符串str1,str2,构造一个最短的字符串S满足大于等于小的字符串,小于大的字符串。
构造方法有两种:
(代码一)一种是根据str1和str2每个字符之间的关系和长度的关系决定S的每个字符。
(代码二)另一种是对S的每个字符进行枚举,直到满足与str1,2的大小关系。
遇到问题:
刚看完题,充满自信,虽然书上已经提醒说了有陷阱,但是我还是觉得应该很快就能搞定,然后就义无反顾的根据第一种构造思路开始写,然后发现全是坑,踩的心累,硬是弄了快一天,期间按照第二种思路写了一遍,感觉跟第一种比太舒爽了。最后还是看了别的博主的代码,才把第一种思路的方法AC。
感悟:
写前多思考1分钟,debug可能就能减少1小时啊!
代码:
代码一:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int MAXN = 1000 + 10;
string name[MAXN], str1, str2;
int n;
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
while (cin >> n && n) {
for (int i = 0; i < n; i++) cin >> name[i];//input
sort(name, name + n); //sorting all the strings by ascending order
str1 = name[n / 2 - 1]; str2 = name[n / 2]; //selecting middle two string,smaller to str1 ,bigger to str2
for (int i = 0; i < str1.length() && i < str2.length(); i++) {
if (str1[i] == str2[i]) cout << str1[i];
else {
if (i == str1.length() - 1) cout << str1[i];
else if (str2[i] - str1[i] > 1 || i != str2.length() - 1) cout << (char)(str1[i] + 1);
else {
cout << str1[i];
for (int j = i+1; j < str1.length(); j++) {
if(j == str1.size() - 1) {
cout << str1[j];
break;
}
if(str1[j] != 'Z') {
cout << (char)(str1[j] + 1);
break;
}
cout << 'Z';
}
}
break;
}
}
cout << endl;
}
return 0;
}
代码二:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int MAXN = 1000 + 10;
string name[MAXN], str1, str2;
int n;
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
while (cin >> n && n) {
string ans, temp;
for (int i = 0; i < n; i++) cin >> name[i];//input
sort(name, name + n); //sorting all the strings by ascending order
str1 = name[n / 2 - 1]; str2 = name[n / 2]; //selecting middle two string,smaller to str1 ,bigger to str2
bool find_ok = false;
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < 26; j++) {
temp =ans + char(j + 65);
if (temp >= str1 && temp < str2) {
ans = temp;
find_ok = true; break;
}
}
if (find_ok) break;
temp = ans += str1[i];
}
cout << ans<< endl;
}
return 0;
}