uva 112 Tree Summing

这题老实说处理输入就是一大问题,到网上看了报告,,某些大牛的代码既简短,又好理解,本人先膜拜之~

首先用cin读会忽略space  enter所以首选cin

再者每一次递归时,首先读入一个字符, 然后下一个不知道是字符还是数字,,这里如果你假想要读入数字,结果却读入字符,读入失败,这时要用到一个clear函数,清空你的fail状态, 可以使你继续读入字符,详情请见代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <stack>
#include <queue>
using namespace std;
#define N 300
#define Dbag printf("haha\n");

int S, flag;

bool dfs(int sum) //false表示到头了,也就是false的上一层或许是叶子
{                 // ture表示还可以向下延展
    char ch;
    int v;
    cin>>ch;
    if((cin>>v))
    {
        bool t = dfs(sum+v)|dfs(sum+v); //如果左右儿子都到头,那么当前节点为叶子
        if(!t)if(sum+v==S)flag = 1;   //注意不能用||因为会导致如果左边为true的话,右边不执行
        cin>>ch;
        return true;
    }
    else
    {
        cin.clear();
        cin>>ch;
        return false;
    }
}
int main()
{
    while(cin>>S)
    {
        flag = 0;
        dfs(0);
        if(flag)
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值