UVa 112 - Tree Summing(树的各路径求和,递归)
2015-12-15 21:58
696 查看
题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=48
This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property.
Binary trees are represented in the input file as LISP S-expressions having the following form.
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.
下面给出代码:
其他方法:
使用栈解决的代码:
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:/article/5198174.html 推荐博客2:/article/1736780.html 推荐博客3:/article/3658648.html
下面给出代码:
#include <bits/stdc++.h> #define MAX 100010 using namespace std; char Input() { char str; scanf("%c",&str); while(str == ' ' || str == '\n') scanf("%c",&str); return str; } int work(int v,int *leaf) { int temp, value; scanf("%d",&value); temp = Input(); int max_num=0,left=0,right=0; if(temp == '(') { if(work(v-value,&left)) max_num=1; temp = Input(); if(work(v-value,&right)) max_num=1; temp = Input(); if(left&&right) max_num = (v == value); } else *leaf = 1; return max_num; } int main() { int n,temp; while(~scanf("%d",&n)) { Input(); if(work(n,&temp)) printf("yes\n"); else printf("no\n"); } return 0; }
其他方法:
#include <iostream> #include <string> using namespace std; //递归扫描输入的整棵树 bool ScanTree(int nSum, int nDest, bool *pNull) { static int nChild; //略去当前一级前导的左括号 cin >> (char&)nChild; //br用于递归子节点的计算结果,bNull表示左右子是否为空 bool br = false, bNull1 = false, bNull2 = false; //如果读入值失败,则该节点必为空 if (!(*pNull = ((cin >> nChild) == 0))) { //总和加上读入的值,遍例子节点 nSum += nChild; //判断两个子节点是否能返回正确的结果 br = ScanTree(nSum, nDest, &bNull1) | ScanTree(nSum, nDest, &bNull2); //如果两个子节点都为空,则本节点为叶,检验是否达到目标值 if (bNull1 && bNull2) { br = (nSum == nDest); } } //清除节点为空时cin的错误状态 cin.clear(); //略去当前一级末尾的右括号 cin >> (char&)nChild; return br; } //主函数 int main(void) { bool bNull; //输入目标值 for (int nDest; cin >> nDest;) { //根据结果输出yes或no cout << (ScanTree(0, nDest, &bNull) ? "yes" : "no") << endl; } return 0; }
使用栈解决的代码:
#include <stdio.h> #include <string.h> #define MAXN 10000 int stack[MAXN]; int topc, top, t; bool judge() { int sum = 0; for (int i=1; i<=top; i++) sum += stack[i]; if (sum == t) return true; return false; } int main() { //freopen("f:\\out.txt", "w", stdout); while (scanf("%d", &t) != EOF) { int tmp = 0, flag = 0, isNeg = 0; char pre[4]; topc = top = 0; memset(pre, 0, sizeof (pre)); while (1) { // 接收字符的代码,忽略掉空格和换行 char ch = getchar(); while ('\n'==ch || ' '==ch) ch = getchar(); // 记录该字符前三个字符,便于判断是否为叶子 pre[3] = pre[2]; pre[2] = pre[1]; pre[1] = pre[0]; pre[0] = ch; // 如果遇到左括弧就进栈 if ('(' == ch) { topc++; if (tmp) { if (isNeg) { tmp *= -1; isNeg = 0; } stack[++top] = tmp; tmp = 0; } continue; } // 如果遇到右括弧就出栈 if (')' == ch) { // 如果为叶子便计算 if ('('==pre[1] && ')'==pre[2] && '('==pre[3]) { if (!flag) flag = judge(); } else if (pre[1] != '('){ top--; } topc--; // 如果左括弧都被匹配完说明二叉树输入完毕 if (!topc) break; continue; } if ('-' == ch) isNeg = 1; else tmp = tmp*10 + (ch-'0'); } if (flag) printf("yes\n"); else printf("no\n"); } return 0; }
相关文章推荐
- android gradle 配置
- IOS之UITableView实现Section独立封装
- BaseAdapter-ListView中的item显示多种布局
- MATLAB使用频率方法的运动检测
- Linux with HDMI video output on the ZED, ZC702 and ZC706 boards
- partprobe报错问题解决
- ejabberd_node_groups
- 移动开发博客汇总
- Oracle nls_sort和nlssort 排序功能介绍
- 打印金字塔形杨辉三角
- zzulioj 1841: so easy!麻麻再也不用担心我的数学了! (数学规律)
- leetcode -- Remove Duplicates from Sorted Array II -- 重点
- 智能优化算法总结
- AHCI: Failed to attach drive to Port1 (VERR_GENERAL_FAILURE).
- Func<TResult>委托和Action委托
- 测试计划
- UI16-通过Xcode将代码提交到github上, 把仓库放在github上
- AHCI: Failed to attach drive to Port1 (VERR_GENERAL_FAILURE).
- InputStream 、 InputStreamReader 、 BufferedReader
- 图像编程-图像平移