uva 11258String Partition

来源:互联网 发布:会计毕业论文数据 编辑:程序博客网 时间:2024/05/02 08:37

原题:
John was absurdly busy for preparing a programming contest recently. He wanted to create a ridicu-
lously 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

中文:
给你一个数字组成的字符串,现在让你把这个字符串拆分成几个整数的和最大。单个整数不能超过2的32次幂。

#include<bits/stdc++.h>using namespace std;typedef long long ll;const int maxn=210;const ll inf=2147483647;string s;ll dp[maxn][maxn];int t;int main(){    ios::sync_with_stdio(false);    cin>>t;    while(t--)    {        cin>>s;        memset(dp,0,sizeof(dp));        int n=s.size();        for(int i=0;i<n;i++)        {            dp[i][i]=s[i]-'0';        }        for(int seg=1;seg<=n;seg++)        {            for(int l=0;l<n-seg+1;l++)            {                int r=l+seg-1;                if(seg>10)                    dp[l][r]=-1;                else                {                    string sb=s.substr(l,seg);                    ll tmp=stoll(sb);                    if(tmp>inf)                        dp[l][r]=-1;                    else                        dp[l][r]=tmp;                }                for(int i=l;i<r;i++)                {                    dp[l][r]=max(dp[l][r],dp[l][i]+dp[i+1][r]);                }            }        }        cout<<dp[0][n-1]<<endl;    }    return 0;}

解答:

很简单基础的区间动态规划问题。

设置状态为dp[i][j]表示在使用区间在i到j的字符串所能组成的最大分段整数和是多少?

状态转移方程为dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])

表示区间i到j组成的最大分段整数和可以用枚举i到k以及k+1到j的和来表示。

初始化的时候dp[i][i]=s[i]0 表示区间长度为1的时候,最大和就是单个数字本身

原创粉丝点击