Use the BFS to solve the equation problems(Case : hdu 4403 )
A very hard Aoshu problem
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
2012 ACM/ICPC Asia Regional Jinhua Online
Problem analysis:
Give you a a digit serial,and you task is add one or more "+"and only one "=" to the digit serial to make up a equation.
For this problem,we can use the BFS to solve it.But the key problem is how to handle it.
Here,provide a solution to the problem.
First,we consider all kinds of conditions before "=",and then after "=";if the two parts values are the same,add 1 to the calculation resultss.
#include<iostream>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
char str[30];//读入
int num[30];//转换为数字
int ans;//统计结果
int len;//计算读入字符数组的长度
void BFS_count(int j,int sum,int sum2,int p)//sum代表“=”左边的值 sum2代表右边的值
{
if(j==len)//如果遍历等号右边所有的数 可以开始判断是否相等
{
if(sum==sum2)
ans++;
return ;
}
p=p*10+num[j];
BFS_count(j+1,sum,sum2+p,0);//遍历“=”号右边的数插入等号的情况
if(j+1!=len)//如果没有遍历到最后一个数继续遍历
BFS_count(j+1,sum,sum2,p);//遍历“=”号右边的数不插入等号的情况
}
void BFS(int j,int sum,int p)//j代表插入符号的位置
{
if(j==len-1)
return ;
p=p*10+num[j];
BFS(j+1,sum+p,0);//搜索等号左边插入加号的情况
BFS(j+1,sum,p);//搜索等号左边不插入加号的情况
BFS_count(j+1,sum+p,0,0);//遍历以上所有情况
}
int main()
{
while(gets(str))
{
if(strcmp(str,"END")==0)
break;
len=strlen(str);
int i;
for(i=0;str[i]!='\0';i++)
num[i]=str[i]-'0';
ans=0;
BFS(0,0,0);
cout<<ans<<endl;
}
return 0;
}

浙公网安备 33010602011771号