poj 1950

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值