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 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, Trepresents 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

解题思路:题目给出树一种定义表达式.每组数据给出目标数据target,以及树的结构表达式.要求判断所给的树中是否存在一条路径满足其上节点的和等于target,如果存在输出yes,否则输出no.所给的树属于二叉树,但是不一定是满二叉树,所以对于所给的树进行左右递归计算,如果存在路径满足则输出yes,否则输出no推荐博客1:http://www.cnblogs.com/devymex/archive/2010/08/10/1796854.html推荐博客2:http://blog.csdn.net/zcube/article/details/8545544推荐博客3:http://blog.csdn.net/mobius_strip/article/details/34066019

下面给出代码:

 1 #include <bits/stdc++.h>
 2 #define MAX 100010
 3
 4 using namespace std;
 5
 6 char Input()
 7 {
 8     char str;
 9     scanf("%c",&str);
10     while(str == ‘ ‘ || str == ‘\n‘)
11         scanf("%c",&str);
12     return str;
13 }
14
15 int work(int v,int *leaf)
16 {
17     int temp, value;
18     scanf("%d",&value);
19     temp = Input();
20     int max_num=0,left=0,right=0;
21     if(temp == ‘(‘)
22     {
23         if(work(v-value,&left))  max_num=1;
24         temp = Input();
25         if(work(v-value,&right)) max_num=1;
26         temp = Input();
27         if(left&&right) max_num = (v == value);
28     }
29     else *leaf = 1;
30     return max_num;
31 }
32 int main()
33 {
34     int n,temp;
35     while(~scanf("%d",&n))
36     {
37         Input();
38         if(work(n,&temp))
39             printf("yes\n");
40         else
41             printf("no\n");
42     }
43     return 0;
44 }

其他方法:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 //递归扫描输入的整棵树
 5 bool ScanTree(int nSum, int nDest, bool *pNull) {
 6     static int nChild;
 7     //略去当前一级前导的左括号
 8     cin >> (char&)nChild;
 9     //br用于递归子节点的计算结果,bNull表示左右子是否为空
10     bool br = false, bNull1 = false, bNull2 = false;
11     //如果读入值失败,则该节点必为空
12     if (!(*pNull = ((cin >> nChild) == 0))) {
13         //总和加上读入的值,遍例子节点
14         nSum += nChild;
15         //判断两个子节点是否能返回正确的结果
16         br = ScanTree(nSum, nDest, &bNull1) | ScanTree(nSum, nDest, &bNull2);
17         //如果两个子节点都为空,则本节点为叶,检验是否达到目标值
18         if (bNull1 && bNull2) {
19             br = (nSum == nDest);
20         }
21     }
22     //清除节点为空时cin的错误状态
23     cin.clear();
24     //略去当前一级末尾的右括号
25     cin >> (char&)nChild;
26     return br;
27 }
28 //主函数
29 int main(void) {
30     bool bNull;
31     //输入目标值
32     for (int nDest; cin >> nDest;) {
33         //根据结果输出yes或no
34         cout << (ScanTree(0, nDest, &bNull) ? "yes" : "no") << endl;
35     }
36     return 0;
37 }

使用栈解决的代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define MAXN 10000
 4
 5 int stack[MAXN];
 6 int topc, top, t;
 7
 8 bool judge() {
 9     int sum = 0;
10     for (int i=1; i<=top; i++)
11         sum += stack[i];
12     if (sum == t)
13         return true;
14     return false;
15 }
16
17 int main() {
18
19     //freopen("f:\\out.txt", "w", stdout);
20     while (scanf("%d", &t) != EOF) {
21         int tmp = 0, flag = 0, isNeg = 0;
22         char pre[4];
23         topc = top = 0;
24         memset(pre, 0, sizeof (pre));
25
26         while (1) {
27             // 接收字符的代码,忽略掉空格和换行
28             char ch = getchar();
29             while (‘\n‘==ch || ‘ ‘==ch)
30                 ch = getchar();
31
32             // 记录该字符前三个字符,便于判断是否为叶子
33             pre[3] = pre[2];
34             pre[2] = pre[1];
35             pre[1] = pre[0];
36             pre[0] = ch;
37
38             // 如果遇到左括弧就进栈
39             if (‘(‘ == ch) {
40                 topc++;
41                 if (tmp) {
42                     if (isNeg) {
43                         tmp *= -1;
44                         isNeg = 0;
45                     }
46                     stack[++top] = tmp;
47                     tmp = 0;
48                 }
49                 continue;
50             }
51
52             // 如果遇到右括弧就出栈
53             if (‘)‘ == ch) {
54                 // 如果为叶子便计算
55                 if (‘(‘==pre[1] && ‘)‘==pre[2] && ‘(‘==pre[3]) {
56                     if (!flag)
57                         flag = judge();
58                 }
59                 else if (pre[1] != ‘(‘){
60                     top--;
61                 }
62                 topc--;
63                 // 如果左括弧都被匹配完说明二叉树输入完毕
64                 if (!topc)
65                     break;
66                 continue;
67             }
68             if (‘-‘ == ch)
69                 isNeg = 1;
70             else
71                 tmp = tmp*10 + (ch-‘0‘);
72         }
73
74         if (flag)
75             printf("yes\n");
76         else
77             printf("no\n");
78     }
79
80     return 0;
81 }
时间: 2024-11-03 20:54:15

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

 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 represe

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 10410 - Tree Reconstruction(树)

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

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

Codeforces 618D Hamiltonian Spanning Tree(树的最小路径覆盖)

题意:给出一张完全图,所有的边的边权都是 y,现在给出图的一个生成树,将生成树上的边的边权改为 x,求一条距离最短的哈密顿路径. 先考虑x>=y的情况,那么应该尽量不走生成树上的边,如果生成树上有一个点的度数是n-1,那么必然需要走一条生成树上的边,此时答案为x+y*(n-2). 否则可以不走生成树上的边,则答案为y*(n-1). 再考虑x<y的情况,那么应该尽量走生成树上的边,由于树上没有环,于是我们每一次需要走树的一条路,然后需要从非生成树上的边跳到树的另一个点上去, 显然跳的越少越好,于

HDU 4718 The LCIS on the Tree(树链剖分)

Problem Description For a sequence S1, S2, ... , SN, and a pair of integers (i, j), if 1 <= i <= j <= N and Si < Si+1 < Si+2 < ... < Sj-1 < Sj , then the sequence Si, Si+1, ... , Sj is a CIS(Continuous Increasing Subsequence). The

Tree Summing[UVA-112]

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

[转] Splay Tree(伸展树)

好久没写过了,比赛的时候就调了一个小时,差点悲剧,重新复习一下,觉得这个写的很不错.转自:here Splay Tree(伸展树) 二叉查找树(Binary Search Tree)能够支持多种动态集合操作.因此,在信息学竞赛中,二叉排序树起着非常重要的作用,它可以被用来表示有序集合.建立索引或优先队列等. 作用于二叉查找树上的基本操作的时间是与树的高度成正比的.对一个含n各节点的完全二叉树,这些操作的最坏情况运行时间为O(log n).但如果树是含n个节点的线性链,则这些操作的最坏情况运行时间