uva 112 - Tree Summing

 Tree Summing 

Background

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.

The Problem

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

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.

The Output

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.

Sample Input

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 ()

Sample Output

yes
no
yes
no
#include <iostream>
#include <stack>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <stack>
#include <list>
#include <sstream>

using namespace std;

#define ms(arr, val) memset(arr, val, sizeof(arr))
#define N 1000000
#define INF 0x3fffffff
#define vint vector<int>
#define setint set<int>
#define mint map<int, int>
#define lint list<int>
#define sch stack<char>
#define qch queue<char>
#define sint stack<int>
#define qint queue<int>

struct node
{
    int val;
    int l;
    int r;
    int tag;//建树标志
    void set(int val)
    {
        l = r = 0;
        tag = 2;
        this->val = val;
    }
}tree[N];

char seq[N];
int val, root, p, I;
sint si;

int t;
bool ldigit()//左括号右边是数字,并且移动到下一个左括号位置,如果存在的话
{
    t++;
    if (isdigit(seq[t]))//正数
    {
        val = seq[t] - ‘0‘;
        while (isdigit(seq[++t]))//得到数字
        {
            val = val * 10 + seq[t] - ‘0‘;
        }
        return true;
    }
    if (seq[t] == ‘-‘)//负数
    {
        val = 0;
        while (isdigit(seq[++t]))//得到数字
        {
            val = val * 10 + seq[t] - ‘0‘;
        }
        val = -val;
        return true;
    }
    while (seq[++t] && seq[t] != ‘(‘);
    return false;
}

void getSeq()//读取输入,注意还存在负数的情况,一开始没考虑到
{
    int con = 1, n = 0;
    char ch;
    while (ch = getchar(), ch != ‘(‘);
    seq[n++] = ‘(‘;
    while (con)
    {
        ch = getchar();
        if (ch == ‘(‘)
        {
            con++;
            seq[n++] = ch;
        }
        else
            if (ch == ‘)‘)
            {
                con--;
                seq[n++] = ch;
            }
            else
                if (isdigit(ch))
                {
                    seq[n++] = ch;
                }
                else
                    if (ch == ‘-‘)
                    {
                        seq[n++] = ch;
                    }
    }
    seq[n] = ‘\0‘;
    t = 0;
}

void build()//建树
{
    root = 0;
    if (ldigit())
    {
        tree[++root].set(val);
        si.push(root);
    }
    int pos, tmp;
    while (!si.empty())
    {
        if (ldigit())
        {
            tree[++root].set(val);
            pos = root;
        }
        else
            pos = 0;
        tmp = si.top();
        if (tree[tmp].tag == 2)//左子树
        {
            tree[tmp].l = pos;
            tree[tmp].tag--;
        }
        else//右子树
        {
            tree[tmp].r = pos;
            si.pop();
        }
        if (pos)
        {
            si.push(pos);
        }
    }
}

bool dfs(int i)
{
    bool tag = false;
    val += tree[i].val;
    if (tree[i].l || tree[i].r)
    {
        if (tree[i].l && dfs(tree[i].l))
        {
            return true;
        }
        if (tree[i].r && dfs(tree[i].r))
        {
            return true;
        }
    }
    else
    {
        tag = I == val ? true : false;
    }
    val -= tree[i].val;//放错位置了
    return tag;
}

int main()
{
    //freopen("in.in", "r", stdin);
    while (~scanf("%d", &I))
    {
        getSeq();
        build();
        val = 0;
        if (root && dfs(1))
            puts("yes");
        else
            puts("no");
    }
    return 0;
}

uva 112 - Tree Summing

时间: 2024-08-27 03:33:43

uva 112 - Tree Summing的相关文章

UVA - 112 - Tree Summing (数的求和!栈的应用!)

UVA - 112 Tree Summing Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu Submit Status Description  Tree Summing  Background LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest

UVa 112 - Tree Summing(树的各路径求和,递归)

题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=48 Tree Summing  Background LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the olde

POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)

Tree Summing Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 8132   Accepted: 1949 Description LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, w

UVA Tree Summing

题目如下:  Tree Summing  Background LISP was one of the earliest high-level programming languages and, withFORTRAN, is one of the oldest languages currently being used. Lists,which are the fundamental data structures in LISP, can easily be adaptedto repr

[2016-02-08][UVA][548][Tree]

UVA - 548 Tree Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu Submit Status Description You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root

Tree Summing[UVA-112]

Tree Summing UVA-112 Time Limit:3000ms 这个题主要还是考察对二叉树的理解,刚看到感觉挺简单的,但是做起来却是一个接着一个坑. 首先说一下思路吧.最先想到的是重建整个二叉树,然后对整个树遍历,求出所有从树根到叶子的和,再与题目要求的数进行比较.后来一想其实没必要重建整个树,因为在这个题目的输入下,重建整个树的过程就相当于一次DFS,DFS到底实际上就是达到叶子节点了.因此,一边处理输入一边直接计算求和就行了,满足公式:$s_c=s_p+v_c$,其中$s_c$

uva 10410 - Tree Reconstruction(栈)

题目链接:uva 10410 - Tree Reconstruction 题目大意:给定一个树的BFS和DFS,求这棵树. 解题思路:用栈维护即可.对应BFS序列映射出了每个节点和根节点的距离,遍历dfs序列,对当前节点和栈顶节点比较,如果该节点距离根节点更远,则说明该节点为栈顶节点个孩子节点,则记录后将节点放入栈中.否则弹掉栈顶元素继续比较.需要注意一点,即当元素与栈顶元素的距离值大1的时候要视为相等,因为它们属于兄弟节点 #include <cstdio> #include <cst

UVA 10410 - Tree Reconstruction(树)

UVA 10410 - Tree Reconstruction 题目链接 题意:给定一个树的dfs序列和bfs序列,求出这颗树 思路:拿dfs的序列,分成若干段,每一段相当一个子树,这样就可以利用bfs的序列去将dfs的序列分段,然后利用一个队列去存放每一段,不断求出子树即可.一开始以为parse tree一定是二叉树,原来不一定啊. 代码: #include <cstdio> #include <cstring> #include <vector> #include

uva 558 tree(不忍吐槽的题目名)——yhx

You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path. Input The input