Topic Portal: Maximum Product
The meaning of the question: Give a string of length N only composed of numbers, add k multiplication signs to it, make the product maximum, and output the maximum product.
Solution: Divisional DP, the specifics are not very clear, and this DP has not been systematically studied, but it can be clearly known that this provides the idea of DP on the divisional topic. This problem is very simple, DP equation:
dp[i][j]=max{strToll(s+i-k, k)*dp[i-k][j-1] }
i indicates that the currently processed number string is the first i number of the original input number string
j means insert j multiplication signs into the i number
k means to separate a number of length k from the end of the number string
s is a pointer to the first character of the numeric string
strToll(char a[], b) means to convert the first b elements of the number string a into numbers
Simply put, it is to separate a part from the end of the string as a number and multiply it with the result of adding j-1 multiplication signs to the previous string
Code:
#include<iostream> #include<algorithm> #include<cstdio> #define ll long long using namespace std; ll strToll(char p[], int n) { ll sum = 0; for(char* q = p; q != p+n; ++ q) sum = sum*10 + (*q-'0'); return sum; } ll dp[44][8]; char s[44]; ll DP(int N, int k) { if(dp[N][k]) return dp[N][k]; if(k == 0) return dp[N][k] = strToll(s, N); for(int i = 1; i <= N-k; ++ i) { dp[N][k] = max(dp[N][k], strToll(s+N-i, i)*DP(N-i, k-1)); } return dp[N][k]; } intmain() { #ifdef AFei freopen("in.txt", "r", stdin); #endif int N, k; scanf("%d%d%s", &N, &k, s); printf("%lld\n", DP(N, k)); return 0; }
The idea of divisional DP allows us to use DP to solve this divisional type of problem