程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 11258 String Partition(線性DP)

UVA 11258 String Partition(線性DP)

編輯:C++入門知識

UVA 11258 String Partition(線性DP)


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 signedintegers. 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


Problem setter: Cho
Source: Tsinghua-HKUST Programming Contest 2007

題意就是說有個數字串,讓你拆分成不超過INT_MAX的數。

求最大和。dp[i]:前i個數的最大和。dp[i]=max(dp[k]+sum(k~i)).

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
typedef long long LL;
typedef pairpil;
const int INF = 0x3f3f3f3f;
const int maxn=220;
LL dp[maxn];
char str[maxn];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",str+1);
        int len=strlen(str+1);
        CLEAR(dp,0);
        REPF(i,1,len)
        {
            for(int l=15;l>=1;l--)
            {
                if(i-l<0)  continue;
                LL num=0;
                for(int j=i-l+1;j<=i;j++)
                    num=num*10+str[j]-'0';
                if(num<0||num>INT_MAX)  continue;
                dp[i]=max(dp[i],dp[i-l]+(LL)num);
            }
        }
        printf("%lld\n",dp[len]);
    }
    return 0;
}




  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved