程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
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)


uva 11258 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
6
1234554321
5432112345
000
121212121212
2147483648
11111111111111111111111111111111111111111111111111111

Sample output
1234554321
543211239
0
2121212124
214748372
5555555666

題目大意:給出一串數字序列,要求切割該數列,使得切割出的序列組成的數字小於int類型的最大值(INT_MAX),且切出的數的和最大。

遞推。 dp[i]代表前i個數的最優解。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define N 300
typedef long long ll;
ll dp[N];
int len;
char s[N];
void DP() {
    for (int i = 1; i <= len; i++) {
        for (int j = 1; j <= 10; j++) {
            if (j > i) break;   
            ll sum = 0;
            for (int k = 0; k < j; k++) {
                sum = sum * 10 + s[i - j + k] - '0';
            }
            if (sum >= 0 && sum < INT_MAX) {
                if (dp[i] < dp[i - j] + sum) {
                    dp[i] = dp[i - j] + sum;
                }
            } else break;
        }
    }
}
int main() {
    int T;
    scanf("%d%*c", &T);
    while (T--) {
        scanf("%s", s);
        len = strlen(s);
        memset(dp, 0, sizeof(dp));
        DP();
        printf("%lld\n", dp[len]);
    }
    return 0;
}

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