Uva11258-String Partition (recurrence)
Question: uva11258-String Partition (recurrence)
A series of numbers are composed of many int-type numbers, that is, there is no space in the middle. So I am asking how to split these numbers so that the sum of these numbers is the largest.
Solution: the int type Integer is required here. The maximum value of a single number is 2147483647. dp [I] [j] indicates the maximum sum that can be obtained from the I character to the j character of the numeric string.
Dp [I] [j] = max (dp [I] [I + k] + dp [I + k + 1] [j ]) k> = 0 & k <= j-I-1. it is possible that the last j and the previous n characters constitute an integer to obtain a larger value.
For example, the number 12345678910 may be divided into 1 | 345678912, 12 | 345678910,123 | 45678910,123 4 | 5678910,123 45 | 678910,123 456 | 78910,123 4567 | 8910,123 45678 | 910,123 456789 | 10,123 4567891 | 0. The first division is because | the number that follows has exceeded the maximum value, so we need to divide it into two more numbers. Another possibility is that the length of the number is less than 10, so the number is certainly not the largest. If the value is equal to 10, you need to check whether the value exceeds the maximum value. If the value exceeds 10, you need to divide it.
Code:
#include
#include
typedef long long ll;const int N = 205;const ll maxn = 2147483647;ll dp[N][N];char str[N];char s1[N];char s2[N];int len;ll Max (const ll a, const ll b) { return a > b ? a : b; }ll MaxNum (int j, int l) {ll ans;memcpy (s1, str + j, sizeof (char) * (l + 1));s1[l + 1] = '\0';sscanf (s1, "%lld", &ans);/*if (ans > maxn) {memcpy (s1, str + j + 1, sizeof (str + j + 1));s1[j + l] += str[j];s1[j + l + 1] = '\0';memcpy (s2, str + j, sizeof (str + j));s2[j + l - 1] += str[j + l];s2[j + l] = '\0';if (strcmp (s1, s2) > 0)sscanf (s1, "%lld", &ans);elsesscanf (s2, "%lld", &ans);}*/if (ans > maxn)return -1;return ans;}void init () {for (int i = 0; i < len; i++) dp[i][i] = str[i] - '0'; }int main () { int t;ll ans;ll temp;scanf ("%d", &t);while (t--) {scanf ("%s", str);len = strlen (str);if (len < 10) sscanf (str, "%lld", &ans);else {init();//printf ("%lld\n", MaxNum (0, 9));for (int l = 1; l < len; l++)for (int i = 0; i + l < len; i++) {temp = -1;if (l < 10) temp = MaxNum(i, l);for (int k = 0; k < l; k++) temp = Max (temp, dp[i][i + k] + dp[i + k + 1][i + l]);dp[i][i + l] = temp;}ans = dp[0][len - 1];}printf ("%lld\n", ans);}return 0;}