您的位置:首页 > 产品设计 > UI/UE

Quicksum -SilverN

2016-05-02 16:43 603 查看
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的部分,懒得补了233)

/*Silver_N    quicksum*/
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int n[500];//每个数字
int re[200][200];
int ct=0;//总字符数
int mini=100000;//最小解
int m;//需求数
int ansum=0;
int flag=0;
int ssum(int s,int t){//截取
int i,j;
if(re[s][t])return re[s][t];
//else begin
int x=0;
for(i=s;i<=t;i++){
x=x*10+n[i];
}
re[s][t]=x;
return x;
//end
}
void read1(){//读入
bool flag=0;
char c;
while(scanf("%c",&c)){
if(c=='"')
if(flag==1)break;
else flag=1;
if(c>='0' && c<='9'){
n[++ct]=c-'0';
}
}
return;
}
void dfs(int cpls,int pos){//pos-在第pos个数后插入
//    printf("test  \n");
if(flag==1)return;
if(cpls>mini)return;
int i,j;
int start=pos+1;
for(i=ct;i>=pos+1;i--){//从后往前枚举位置,优先截取较长的串
//        printf("test message: s:%d  t:%d total:%d \n",start,i,ct);
//        printf("    sum:%d  + %d\n",ansum,ssum(start,i));
ansum+=ssum(start,i);
if(ansum>m){
ansum-=ssum(start,i);
continue;}
if(ansum==m && i==ct){
mini=min(mini,cpls);
flag=1;//找到解的标志
}
else
dfs(cpls+1,i);
if(flag==1)return;//找到一解直接退出
ansum-=ssum(start,i);
}
return;
}
int main(){
read1();
cin>>m;
dfs(0,0);
if(mini==100000)cout<<"-1";
else cout<<mini;
return 0;

}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: