A very hard Aoshu problem(dfs或者数位)

时间:2023-12-27 11:27:49

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4403

A very hard Aoshu problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1080    Accepted Submission(s): 742

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
题解:考虑枚举等号的位置,每次dfs等号左侧的值,对应找等号右边是否有对应的相同值,这里一定要注意调用的时候的细节,就是考虑每个位置的标号
也可以将每个数字之间的位置用二进制表示,枚举完等号后,其他的位置0表示不放+号,1表示放
dfs代码:
 #include<cstdio>
#include<cstring>
#include<string>
using namespace std;
char str[];
int val[][];
int len;
int ans; void cal()
{
memset(val,,sizeof(val));
for(int i = ; i < len ; i++)
for(int j = i ; j < len ; j++)
for(int k = i ; k <= j ; k++)
val[i][j] = val[i][j]*+(str[k]-'');
}
void dfsr(int lsum,int pos, int rsum)
{
if(pos>=len)
{
if(rsum==lsum)
ans++;
return ;
}
for(int k = pos+ ; k <= len ; k++)
dfsr(lsum,k,rsum+val[pos][k-]);
}
void dfsl(int equ , int pos , int lsum)
{
if(pos>=equ)
dfsr(lsum,equ,);
for(int k = pos+ ; k <= equ ; k++)
dfsl(equ,k,lsum+val[pos][k-]);
} int main()
{
while(~scanf("%s",str)&&str[]!='E')
{
ans = ;
len = strlen(str);
cal();
int equ;
for(equ = ; equ < len ; equ++)
dfsl(equ,,);
printf("%d\n",ans);
}
return ;
}

数位:

 #include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define N 17
char a[N];
int equ;
int len;
bool ck(int sum)
{
int l= , r=;
int cur = ;
for(int i = ; i <= equ ;i++)
{
if(sum&(<<i)) {
cur = cur * + a[i]-'';
l+=cur;
cur = ;
}
else cur = cur*+a[i]-'';
}
if(cur != ) l+=cur;
cur = ;
for(int i = equ+ ; i< len ; i++)
{
if(sum&(<<i)){
cur = cur * + a[i]-'';
r+=cur;
cur = ;
}
else cur = cur*+a[i]-'';
}
if(cur!=) r += cur;
if(l==r) return true;
else return false;
}
int main()
{
while(~scanf("%s",a)&&a[]!='E')
{
int ans = ;
len = strlen(a);
for( equ = ; equ < len- ; equ++)
{
int tm = <<(len-);
for(int j = ; j < tm ;j++)
{
if(ck(j)){
ans++;
// printf("%d %d\n", equ, j);
}
}
}
printf("%d\n",ans>>);
}
return ;
}