uva 112

题意:求构造的树,是否有一条路和为给定值。。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct tree
{
    int value;
    struct tree *lchild;
    struct tree *rchild;
};
tree *root;
bool found;
int I;

int tonum(char *s)
{
    int len = strlen(s);
    int re = 0 ;
    int i = 0 ;
    if (s[0] == '-')
        i++;
    for ( ; i < len ; i++)
        re = re*10 + s[i] - '0';
    if (s[0] == '-')
        re = -re;
    return re = 0 ? -999999:re ;    //0是不可取的  
}

void build(tree *&ch) //引用根节点,不失为一种处理树的根节点的好方法
{
    char c;
    char str[100];
    int count = 0;
    bool isnum = false ;
    while (cin>>c)
    {
        if ((c>='0'&c<='9') | c == '-')
        {
            isnum = true;
            str[count++] = c ;
            str[count] = '\0';  // notice 
        }
        else if ( !isnum && c == ')')  // 叶节点标记是()
        {
            ch = NULL ;
            return ;
        }
        else if (isnum && !(c>='0'&&c<='9'))
        {
            if (tonum(str) == -999999)
                return ;
            ch = new tree;
            ch->value = tonum(str);
            char c11;
            build(ch->lchild);
            build(ch->rchild);
            while (cin>>c11)
            {
                if (c11 == ')')
                    return ;
            }
            return ;
        }
    }
}

void dfs(tree *a,int n)
{
    if (found)   // 深搜的结果是最后的解
        return ;
    if (!a->lchild && !a->rchild)
    {
        if (n+a->value == I)
            found = true;
        return ;
    }
    if (a->lchild) dfs(a->lchild,n+a->value);
    if (a->rchild) dfs(a->rchild,n+a->value);
}

int main()
{
    while ( cin>>I )
    {
        getchar();
        root = NULL ;
        build(root);
        if (!root)
        {
            cout<<"no"<<endl;
            continue;
        }
        found = false ;
        dfs(root,0);
        if (found)
            cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
    return 0;
}

大神的递归做法:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int flag ;
int t_sun(int n,int sum)
{
	int data;
	char c;
	cin>>c;   //左括号 
	cin>>data;
	if(!(cin == 0))
	{
		sum +=data;
		int ok1 = t_sum(n,sum);
		int ok2 = t_sum(n,sum);
		if(!ok1 && !ok2 && !flag)
			if(sum == n)
				flag = 1;
		cin>>c ;  //右括号
		return 1;
	}
	else 
	{
		cin.clear();
		cin>>c ;  // notice 
		return 0 ;
	}
}
int main()
{
	int n;
	while(cin>>n)
	{
		flag = 0 ;
		t_sum(n,0);
		cout<<(flag?"yes":"no")<<endl;
	}
	return 0 ;
}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值