quicksum
Queation:
Given a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual. For example, consider the string "12" (quotes for clarity). With zero additions, we can achieve the number 12. If we insert one plus sign into the string, we get "1+2", which evaluates to 3. So, in that case, given "12", a minimum of 1 addition is required to get the number 3. As another example, consider "303" and a target sum of 6. The best strategy is not "3+0+3", but "3+03". You can do this because leading zeros do not change the result.
Write a class QuickSums that contains the method minSums, which takes a String numbers and an int sum. The method should calculate and return the minimum number of additions required to create an expression from numbers that evaluates to sum. If this is impossible, return -1.
example:
"382834"
100
Returns: 2
There are 3 ways to get 100. They are 38+28+34, 3+8+2+83+4 and 3+82+8+3+4. The minimum required is 2.
Constraints
- numbers will contain between 1 and 10 characters, inclusive.
- Each character in numbers will be a digit.
- sum will be between 0 and 100, inclusive.
- the string will be shorter than 100 bit.
---------------------------------------------我是分割线--------------------------------------------------------------
本题有多种方法,例如“记忆化搜索+剪枝”,但我用的是DP。
由于数据太弱(加号数小于10,和不大于100……)所以开个三维数组dp[i][j][k]。
i、j表示字符串从i开始到j表示的数;
k表示此时和为k;
数组内存放所需加号数。
不多说,上代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<cmath> 6 #include<algorithm> 7 #include<cstdlib> 8 using namespace std; 9 int cut(string,int,int); 10 int read(){ 11 int x=0,f=1;char ch=getchar(); 12 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} 13 while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} 14 return x*f; 15 } 16 long long chang=0; 17 int dp[101][101][101]; 18 int main() 19 { 20 string s;long long sum;long long ans=0; 21 cin>>s; 22 chang=s.length(); 23 cin>>sum; 24 for(int i=0;i<=100;i++) 25 for(int j=0;j<=100;j++) 26 for(int k=0;k<=100;k++) 27 dp[i][j][k]=11; 28 // cout<<dp[0][chang-1][sum]<<endl; 29 for(int i=0;i<chang;i++) 30 for(int j=0;i+j<chang;j++) 31 { 32 long long num=cut(s,i,i+j); 33 if(num<=sum) dp[i][i+j][num]=0; 34 } 35 // cout<<dp[0][chang-1][sum]<<endl; 36 for(int i=1;i<chang;i++) //数长 37 for(int head=0;head+i<chang;head++) //始位 38 for(int j=0;j<=sum;j++) //和 39 for(int k=head;k<head+i;k++) //加号位 40 for(int ss=0;j-ss>0;ss++) //中间和 41 dp[head][head+i][j]=min((dp[head][k][j-ss]+dp[k+1][head+i][ss])+1,dp[head][head+i][j]); 42 ans=dp[0][chang-1][sum]; 43 if(ans==11) ans=-1; 44 cout<<ans; 45 return 0; 46 } 47 int cut(string s,int a,int b) 48 { 49 long long n=0; 50 for(int i=a;i<=b;i++) 51 n=n*10+(s[i]-‘0‘); 52 return n; 53 }