给定一个n,求由1到n的数经过'+','-'或'.'三种运算后值为0的方法数。
并输出前20组答案,若不足20组,输出全部。
这题思路肯定是DFS,在处理搜索出来的式子时会有些麻烦。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n,a[15],ans;
int calc()
{
int i,t,cnt;
i=1;
t=1;
cnt=0;
while (a[i] == '.')
{
if (i >= 9)
t*=100;
else
t*=10;
t+=i+1;
i++;
}
cnt=t;
for (;i<n;)
{
if (a[i] == '+')
{
t=i+1;
i++;
while(a[i] == '.' && i<n)
{
if (i >= 9)
t*=100;
else
t*=10;
t+=i+1;
i++;
}
cnt+=t;
}
else
{
t=i+1;
i++;
while(a[i] == '.' && i<n)
{
if (i >= 9)
t*=100;
else
t*=10;
t+=i+1;
i++;
}
cnt-=t;
}
}
return cnt;
}
int dfs(int p)
{
int i;
if (p == n)
{
a[0]='+';
if (calc() == 0)
{
if (ans < 20)
{
for (i=1; i<=n; i++)
{
if (i == 1)
{
printf("%d",i);
continue;
}
printf(" %c",a[i-1]);
printf(" %d",i);
}
printf("\n");
}
ans++;
}
return 0;
}
a[p]='+';
dfs(p+1);
a[p]='-';
dfs(p+1);
a[p]='.';
dfs(p+1);
}
int main()
{
while (scanf("%d",&n) != EOF)
{
ans=0;
dfs(1);
printf("%d\n",ans);
return 0;
}
}
本文介绍了一个使用深度优先搜索(DFS)算法解决特定数学问题的C++实现:给定一个整数n,寻找从1到n的所有数字通过添加'+'、'-'或'.'运算符使得表达式的值等于0的所有可能组合,并输出前20组解或所有解。文章详细展示了如何遍历所有可能的组合,并计算最终的表达式值。
836

被折叠的 条评论
为什么被折叠?



