UVA_11258_StringPartition
来源:互联网 发布:芒果tv有Mac 版吗 编辑:程序博客网 时间:2024/06/06 19:01
String Partition
Description
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
Sample output
1234554321
543211239
0
2121212124
214748372
5555555666
一个区间dp的问题
用区间dp容易超时
以下是区间dp
更简单的做法是最多十个数字一段的处理,以后补充
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;typedef long long LL;const int M=205;const LL MM=((LL)1<<31)-1; //32位intchar num[M];LL numn[M][M];LL dp[M][M];LL getnum(int i,int j){ LL co=0; LL p=1; for(int k=j;k>=i;k--) { co+=(num[k]-'0')*p; p*=10; if(co>MM) //超过最大值的数用不到所以不用继续求下去了 return co; } return co;}int main(){ int t; //freopen("1.in","r",stdin); scanf("%d",&t); while(t--) { scanf("%s",num+1); memset(dp,0,sizeof(dp)); int len=strlen(num+1); for(int i=1;i<=len;i++) dp[i][i]=num[i]-'0'; for(int i=1;i<=len;i++) for(int j=i;j<=len;j++) { numn[i][j]=getnum(i,j); } for(int l=2;l<=len;l++) { for(int st=1;st<=len-l+1;st++) { for(int mi=st;mi<=st+l-1;mi++) { LL t=numn[st][mi]; if(t>MM) //更长的数字只会更大不需要用到了 break; dp[st][st+l-1]=max(dp[st][st+l-1],t+dp[mi+1][st+l-1]); } } } printf("%lld\n",dp[1][len]); //别写%I64d } return 0;}