Uva--11258(动规,记忆化搜索,枚举)
2014-08-25 01:12:35
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
1234554321
5432112345
000
121212121212
2147483648
11111111111111111111111111111111111111111111111111111
Sample output
543211239
0
2121212124
214748372
5555555666
1 /************************************************************************* 2 > File Name: h.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Thu 21 Aug 2014 10:15:36 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 typedef long long ll; 16 const ll INF = ((ll)1 << 31) - 1; 17 18 ll dp[205]; 19 char s[205]; 20 int v[205]; 21 int n; 22 int len; 23 24 ll Solve(int p){ 25 if(dp[p] != -1) 26 return dp[p]; 27 if(p == 0) 28 return 0; 29 dp[p] = INF; 30 ll sum = 0; 31 ll base = 1; 32 ll tmax = -1; 33 for(int i = p; i >= 1; --i){ 34 sum += v[i] * base; 35 base *= 10; 36 if(sum > INF) 37 break; 38 if(v[i] || i == p){ 39 tmax = max(tmax,Solve(i - 1) + sum); 40 } 41 } 42 return dp[p] = tmax; 43 } 44 45 int main(){ 46 scanf("%d",&n); 47 while(n--){ 48 scanf("%s",s + 1); 49 len = strlen(s + 1); 50 for(int i = 1; i <= len; ++i){ 51 v[i] = s[i] - '0'; 52 } 53 memset(dp,-1,sizeof(dp)); 54 printf("%lld\n",Solve(len)); 55 } 56 return 0; 57 }