百练1145:Tree Summing

总时间限制: 
1000ms
内存限制: 
65536kB
描述
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees. 

This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property. 
Given a binary tree of integers, you are to write a program that determines whether there exists a root-to-leaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18. 

Binary trees are represented in the input file as LISP S-expressions having the following form. 

empty tree ::= ()

tree ::= empty tree (integer tree tree)

The tree diagrammed above is represented by the expression (5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) ) 

Note that with this formulation all leaves of a tree are of the form (integer () () ) 

Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively. 
输入
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression as described above. All binary tree S-expressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by end-of-file.
输出
There should be one line of output for each test case (integer/tree pair) in the input file. For each pair I,T (I represents the integer, T represents the tree) the output is the string yes if there is a root-to-leaf path in T whose sum is I and no if there is no path in T whose sum is I.
样例输入
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3 
     (2 (4 () () )
        (8 () () ) )
     (1 (6 () () )
        (4 () () ) ) )
5 ()
样例输出
yes
no
yes
no
来源   Duke Internet Programming Contest 1992,UVA 112 分析   题目大意是根据输入的字符串建立二叉树,计算从根出发到叶节点路径上的结点之和,假如这些和中有等于I的,则输出“yes”,否则输出“no”   这道题关键在于处理输入和建树,由于输入不只是一行字符串,而是多行,因此需要进行“括号匹配”,括号匹配结束,输入处理结束。   我的方法是输入和建树分开处理,用栈来进行括号匹配;看了看别人的代码,是边处理字符边建的树,更为简洁,值得学习: http://blog.csdn.net/keshuai19940722/article/details/9666869 我的代码:
#include <cstdio>
#include <stack>
#include <string>
#include <cctype>
#include <cstring>
using namespace std;
//(5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
int loc,n;
bool mark[500];
//char buf[500];
string buf;
bool success;
struct Node{
    int x;
    Node *lchild;
    Node *rchild;
}tree[1002];
Node *create(int z){
    tree[loc].x = z;
    tree[loc].lchild = NULL;
    tree[loc].rchild = NULL;
    return &tree[loc++];
}
Node *buildTree(int x,int y){
        int i = x;
        while(i < buf.length())
            if(buf[i] == '(')break;
            else i++;
        Node *p;
        //while(buf[i] == ')')i++;
        if(buf[i] == '('){
            mark[i] = true;
            if(buf[i+1] == ')')return NULL;
            else{
                int d = 0;
                bool minus = false;
                if(buf[i+1] == '-'){minus = true;i++;}
                while(isdigit(buf[i+1])){
                    d = 10*d + buf[i+1] - '0';
                    i++;
                }
                i++;
                if(minus)d = -d;
                p = create(d);
                p->lchild = buildTree(i,y);
                int r = i;
                for(;r <= y;r++)
                    if(mark[r] == false && buf[r] == '(')break;
                p->rchild = buildTree(r,y);
                return p;
            }
        }
}
void DFS(Node *p,int ans){
    if(p == NULL)return;
    ans += p->x;
    if(p->lchild == NULL && p->rchild == NULL){
        if(ans == n){
            success = true;
        }
        return;
    }
    if(p->lchild && !success)
        DFS(p->lchild,ans);
    if(p->rchild && !success)
        DFS(p->rchild,ans);
}

int main(){
    while(scanf("%d",&n) != EOF){
        memset(mark,0,sizeof(mark));
        //fgets(buf,sizeof(buf),stdin);
        char temp[256];
        buf = "";
        stack<int> s;
        bool End = false;
        while(true){
            scanf("%s",temp);
            int len = strlen(temp);
            for(int i = 0;i < len;i++){
                if(temp[i] == '(')
                    s.push(1);
                if(temp[i] == ')'){
                    s.pop();
                    if(s.empty()){
                        End = true;
                        break;
                    }
                }
            }
            buf += temp;
            if(End == true)break;
        }
        //printf("%s\n",buf.c_str());

        Node *root = buildTree(0,buf.length()-1);
        success = false;
        DFS(root,0);
        if(success == true)printf("yes\n");
        else printf("no\n");
    }
}

转载于:https://www.cnblogs.com/starryxsky/p/7118614.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值