NYOJ 746 整數劃分(四)區間DP
阿新 • • 發佈:2019-01-01
/*
區間dp,設dp[i][j] 表示在區間[0, i]之中,插入j個乘號可以得到的最大數
設a[i][j]為區間[i,j]所形成的數
所以 dp[i][j] = max(dp[k][j-1] * a[k + 1][i])
注意數的範圍,用int不夠
*/
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
long long dp[22][22];
long long a[22][22];
char str[22];
int main()
{
int len, t, m;
scanf("%d", &t);
while (t--)
{
scanf("%s%d", str, &m);
len = strlen(str);
m--;
memset (a, 0, sizeof(a));
memset (dp, 0, sizeof(dp));
for (int i = 0; i < len; i++) //先對a進行預處理,減少複雜度,a[i][j]表示第i段到第j段的數值
{
a[i][i] = str[i] - '0';
for (int j = i + 1; j < len; j++)
{
a[i][j] = a[i][j - 1] * 10 + str[j] - '0';
}
}
for (int i = 0; i < len; i++)
{
dp[i][0] = a[0][i];
}
for (int j = 1; j <= m; j++)
{
for (int i = j; i < len; i++)
{
for (int k = 0; k < i; k++)
{
dp[i][j] = max(dp[i][j], dp[k][j - 1] * a[k + 1][i]);
}
}
}
printf("%lld\n", dp[len - 1][m]);
}
return 0;
}
區間dp,設dp[i][j] 表示在區間[0, i]之中,插入j個乘號可以得到的最大數
設a[i][j]為區間[i,j]所形成的數
所以 dp[i][j] = max(dp[k][j-1] * a[k + 1][i])
注意數的範圍,用int不夠
*/
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
long long dp[22][22];
long long a[22][22];
char str[22];
int main()
{
int len, t, m;
scanf("%d", &t);
while (t--)
{
scanf("%s%d", str, &m);
len = strlen(str);
m--;
memset (a, 0, sizeof(a));
memset (dp, 0, sizeof(dp));
for (int i = 0; i < len; i++) //先對a進行預處理,減少複雜度,a[i][j]表示第i段到第j段的數值
{
a[i][i] = str[i] - '0';
for (int j = i + 1; j < len; j++)
{
a[i][j] = a[i][j - 1] * 10 + str[j] - '0';
}
}
for (int i = 0; i < len; i++)
{
dp[i][0] = a[0][i];
}
for (int j = 1; j <= m; j++)
{
for (int i = j; i < len; i++)
{
for (int k = 0; k < i; k++)
{
dp[i][j] = max(dp[i][j], dp[k][j - 1] * a[k + 1][i]);
}
}
}
printf("%lld\n", dp[len - 1][m]);
}
return 0;
}