John was absurdly busy for preparing a programming contest recently. He wanted to create a ridiculously easy problem for the contest. His problem was not only easy, but also boring: Given a list of non-negative integers, what is the sum of them?
However, he made a very typical mistake when he wrote a program to generate the input data for his problem. He forgot to print out spaces to separate the list of integers. John quickly realized his mistake after looking at the generated input file because each line is simply a string of digits instead of a list of integers.
He then got a better idea to make his problem a little more interesting: There are many ways to split a string of digits into a list of non-zero-leading (0 itself is allowed) 32-bit signed integers. What is the maximum sum of the resultant integers if the string is split appropriately?
Input
The input begins with an integer N ( ≤ 500) which indicates the number of test cases followed. Each of the following test cases consists of a string of at most 200 digits.
Output
For each input, print out required answer in a single line.
Sample input
6
1234554321
5432112345
000
121212121212
2147483648
11111111111111111111111111111111111111111111111111111
1234554321
5432112345
000
121212121212
2147483648
11111111111111111111111111111111111111111111111111111
Sample output
1234554321
543211239
0
2121212124
214748372
5555555666
543211239
0
2121212124
214748372
5555555666
题意:给一串数字。求把数字分割成不大于INT_MAX的数字,使得数字之和最大。
思路:一开始想当然,直接区间dp去写,结果跑的时间不理想。然后看了别人的思路。觉得不错。
i代表前i个数字。j表示划分j个数字。dp[i]表示前i个数字的最优情况。 这样一来从左往右遍历过去。dp[len]即为答案。
代码:
#include <stdio.h>
#include <string.h>
#include <limits.h>
int t, i, j, k, l;
long long dp[205];
char str[205];
long long max(long long a, long long b) {
return a > b ? a : b;
}
int main() {
scanf("%d%*c", &t);
while (t --) {
memset(dp, 0, sizeof(dp));
gets(str);
int len = strlen(str);
for (i = 1; i <= len; i++) {
for (j = 1; j <= 10 && j <= i; j ++) {
long long num = 0;
for (k = 0; k < j; k ++) {
num = num * 10 + str[i - j + k] - '0';
if (num >= 0 && num <= INT_MAX) {
dp[i] = max(dp[i], dp[i - j] + num);
}
else
break;
}
}
}
printf("%lld\n", dp[len]);
}
return 0;
}