雷电
时间限制(普通/Java):1000MS/3000MS 运行内存限制:65536KByte
总提交:111 测试通过:23
总提交:111 测试通过:23
描述
Bob最喜欢玩“雷电”游戏了,不论是手机上还是电脑上还是电游室。游戏过程中,自己控制的飞机存在三次机会,也就是说可以死亡三次。Bob为了向同伴们炫耀自己的技术,他会将一局游戏中飞机死亡时的分数记录下来写在本子上。可bob后面才发现自己由于比较匆忙,把所有的得分(不含前置0)都挨个记录下来中间不存在空格。他不知道三次得分分别是多少了,现在他想知道在已知的这个数字串中,自己三次得分之和最大为多少。每次得分不超过1000000 (106)。
输入
输入有多组测试数据。
每组测试数据由一个bob记录的数字串组成。数字串的长度不超过30。
输出
每组数据输出bob可能的最大得分是多少。如果所记录的数字串是错误的,不能够产生3个得分,则输出 -1 。
样例输入
1234
9000
0009
9000
0009
样例输出
37
90
-1
90
-1
提示
第一个样例可以分成1,2,34。
第二个样例只能够分成90,0,0。
第三个样例是不正确的,无论怎样分,都会导致前置0的出现。
此问题我参考了 http://blog.csdn.net/zhangweiacm/article/details/10226721
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<string>
using std::string;
const int MAX_SCORE = 1000000;
string scoreString; //分数字符串
string::size_type len; //分数字符串的长度
int toInteger(const string& str){
int result(0);
string::size_type len(str.length());
for (string::size_type ix(0); ix != len; ++ix){
result = result * 10 + (str[ix] - '0');
}
return result;
}
int calculateScore(const string::size_type& pos1, const string::size_type& pos2){
//返回由pos1,pos2分割的总分,当出现不合法的分数时,返回-1
if ((pos1 != 1 && scoreString[0] == '0')
|| (pos2 - pos1 != 1 && scoreString[pos1] == '0')
|| (len - pos2 != 1 && scoreString[pos2] == '0')){
return -1; //在转化为数字前检查各个分数是否存在前置零
}
if (pos1 > 7 || pos2 - pos1 > 7 || len - pos2 > 7){
return -1; //防止出现不合法的大数
}
int score1(toInteger(scoreString.substr(0, pos1)));
int score2(toInteger(scoreString.substr(pos1, pos2 - pos1)));
int score3(toInteger(scoreString.substr(pos2)));
if (score1 > MAX_SCORE || score2 > MAX_SCORE || score3 > MAX_SCORE){
return -1; //检查各个分数是否超过限制
}
return score1 + score2 + score3;
}
int main(void){
string::size_type pos1, pos2; //第二个和第三个分数的起始位置
int score; //存储当前的总分
int maxScore; //存储当前总分的最大值
while (cin >> scoreString){
maxScore = -1;
len = scoreString.length();
if (len < 3){ //分数字符串小于3的肯定是错误字符串
cout << maxScore << endl;
continue;
}
for (pos1 = 1; pos1 != len - 1; ++pos1){
for (pos2 = pos1 + 1; pos2 != len; ++pos2){
score = calculateScore(pos1, pos2);
if (score > maxScore){
maxScore = score;
}
}
}
cout << maxScore << endl;
}
return 0;
}