Quicksum -SilverN
Posted 报告振兴哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Quicksum -SilverN相关的知识,希望对你有一定的参考价值。
quicksum
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.
Examples
0)
"99999"
45
Returns: 4
In this case, the only way to achieve 45 is to add 9+9+9+9+9. This requires 4 additions.
1)
"0123456789" 01+2+3+4+5+6+7+8+9
45
Returns: 8
DFS解法
1 #include<algorithm> 2 #include<iostream> 3 #include<cmath> 4 #include<cstdio> 5 using namespace std; 6 int n[500];//每个数字 7 int re[200][200]; 8 int ct=0;//总字符数 9 int mini=10000;//最小解 10 int m;//需求数 11 int ansum=0; 12 int ssum(int s,int t){ 13 int i,j; 14 if(re[s][t])return re[s][t]; 15 //else begin 16 int x=0; 17 for(i=s;i<=t;i++){ 18 x=x*10+n[i]; 19 } 20 re[s][t]=x; 21 return x; 22 //end 23 } 24 void read1(){ 25 bool flag=0; 26 char c; 27 while(scanf("%c",&c)){ 28 if(c==‘"‘) 29 if(flag==1)break; 30 else flag=1; 31 if(c>=‘0‘ && c<=‘9‘){ 32 n[++ct]=c-‘0‘; 33 } 34 } 35 return; 36 } 37 void dfs(int cpls,int pos){//pos-在第pos个数后插入 38 // printf("test \n"); 39 if(cpls>mini)return; 40 int i,j; 41 int start=pos+1; 42 for(i=pos+1;i<=ct;i++){ 43 // printf("test message: s:%d t:%d total:%d \n",start,i,ct); 44 // printf(" sum:%d + %d\n",ansum,ssum(start,i)); 45 ansum+=ssum(start,i); 46 if(ansum>m){ 47 ansum-=ssum(start,i); 48 break;} 49 if(ansum==m && i==ct){ 50 mini=min(mini,cpls); 51 } 52 else 53 dfs(cpls+1,i); 54 ansum-=ssum(start,i); 55 } 56 return; 57 } 58 int main(){ 59 read1(); 60 cin>>m; 61 dfs(0,0); 62 cout<<mini; 63 return 0; 64 65 }
以上是关于Quicksum -SilverN的主要内容,如果未能解决你的问题,请参考以下文章