题目链接:http://poj.org/problem?id=1950
dfs完全不会。。。知道思路,写不出来,没用,能写出来,不熟,没用。。。
//1950 Accepted 164K 94MS C 1165B
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 20
int n;
char str[M];
int ans;
void dfs(int dep,int dep_pre_pre_sum,int dep_pre,int add_sub)
{
if(dep == n+1)
{
if(dep_pre_pre_sum + add_sub * dep_pre == 0)
{
if( ans < 20 )//输出前20个
{
int i;
for( i = 0; i< dep -2; i++ )
printf( "%d %c ", i+1, str[i] );
printf("%d\n",i+1);
}
ans ++;
}
return ;
}
str[dep - 2] = '+';
//比如:有1-2-3-4搜到第四层时,dep_pre_pre_sum保留的是1-2的结果,dep_pre是3的值
//搜索下一层,即1-2-3-4-5时,dep_pre_pre_sum该保留1---3的结果,
//故用dep_pre_pre_sum + dep_pre * add_sub即1--3层来更新dep_pre_pre_sum,dep更新dep_pre
dfs(dep+1,dep_pre_pre_sum + dep_pre * add_sub,dep,1);
str[dep - 2] = '-';
dfs(dep+1,dep_pre_pre_sum + dep_pre * add_sub,dep,-1);
str[dep - 2] = '.';
if(dep < 10)
{
dfs(dep+1,dep_pre_pre_sum,dep_pre*10 + dep,add_sub);
}
else //10以上 8.10 ==>8*100+10
{
dfs(dep+1,dep_pre_pre_sum,dep_pre*100 + dep,add_sub);
}
}
//思路是:dfs
//比如1--2--3---4---5--6---7搜索到第7层,使用用1-----5的结果+/-/.上 6和7运算结果,所以要照顾3层
int main()
{
int dep; //深度
int add_sub; //是加还是减
int dep_pre; //当前搜索深度的前一个 例子中的6
int dep_pre_pre_sum; //例子中的1----5层运算后的结果
while(scanf("%d",&n) != EOF)
{
ans = 0;
dep = 0;
add_sub = 0;
dep_pre = 0;
dep_pre_pre_sum = 0;
memset(str,0,sizeof(str));
dfs(2,0,1,1);
printf("%d\n",ans);
}
return 0;
}