您的位置:首页 > 其它

HDU - 4403 - A very hard Aoshu problem (DFS)

2017-11-09 21:07 399 查看


A very hard Aoshu problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1740    Accepted Submission(s): 1197

Problem Description

Aoshu is very popular among primary school students. It is mathematics, but much harder than ordinary mathematics for primary school students. Teacher Liu is an Aoshu teacher. He just comes out with a problem to test his students:

Given a serial of digits, you must put a '=' and none or some '+' between these digits and make an equation. Please find out how many equations you can get. For example, if the digits serial is "1212", you can get 2 equations, they are "12=12" and "1+2=1+2".
Please note that the digits only include 1 to 9, and every '+' must have a digit on its left side and right side. For example, "+12=12", and "1++1=2" are illegal. Please note that "1+11=12" and "11+1=12" are different equations.

 

Input

There are several test cases. Each test case is a digit serial in a line. The length of a serial is at least 2 and no more than 15. The input ends with a line of "END".

 

Output

For each test case , output a integer in a line, indicating the number of equations you can get.

 

Sample Input

1212
12345666
1235
END

 

Sample Output

2
2
0

 

Source

2012 ACM/ICPC Asia Regional Jinhua Online 

 

题意:用一个等号'='将一串数字分为两份,每部分中的任意两个数字中都可以插入'+'号,求一共有多少种组合使得等式成立

思路:对等号的每一个位置DFS左端所有情况 然后在每种情况继续遍历等号右端所有情况

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#define LL long long
using namespace std;
char s[20];
int num[20],len;
LL ans,mx;
//右侧等式DFS加号
void dfs2(int x,int ed,int sum,int su,int lsum){
if(sum+su>lsum) return;
if(x==ed+1){
if(sum+su==lsum)
ans++;
return;
}
dfs2(x+1,ed,sum,su*10+num[x],lsum);
dfs2(x+1,ed,sum+su,num[x],lsum);
}
//左侧等式DFS+号
void dfs(int x,int ed,int sum,int su){
if(sum+su>mx) return;
if(x==ed+1){
dfs2(x+1, len-1, 0, num[x], sum+su);
return;
}
dfs(x+1,ed,sum,su*10+num[x]);//选择不放+
dfs(x+1,ed,sum+su,num[x]);//放+ 该段已经结束 su加入sum
}

int main()
{
while(scanf("%s",s)){
if(!strcmp(s, "END")) break;
ans = 0;
len = (int)strlen(s);
for(int i=0;i<len;i++) num[i] = s[i] - '0';
for(int i=0;i<len-1;i++){
mx = 0;
for(int j=i+1;j<len;j++){
mx = mx*10 + num[j];
}
dfs(1,i,0,num[0]);
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: