Uva--11258(动规,记忆化搜索,枚举)

2014-08-25 01:12:35

Problem F - String Partition

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

1234554321 
543211239 

2121212124 
214748372 
5555555666
 
思路:由于之前写过的题目思想类似,所以这题写着不费劲,1A。
记忆化搜索,dp[i]表示前 i 个数字所能组成的最大和,枚举最后 k 个数字组成一个多位数,然后进入下一层搜索。
 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 }

 

posted @ 2014-08-25 01:15  Naturain  阅读(174)  评论(0编辑  收藏  举报