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, 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
下面给出代码:
#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=,left=,right=;
if(temp == '(')
{
if(work(v-value,&left)) max_num=;
temp = Input();
if(work(v-value,&right)) max_num=;
temp = Input();
if(left&&right) max_num = (v == value);
}
else *leaf = ;
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 ;
}
其他方法:
#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) == ))) {
//总和加上读入的值,遍例子节点
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(, nDest, &bNull) ? "yes" : "no") << endl;
}
return ;
}
使用栈解决的代码:
#include <stdio.h>
#include <string.h>
#define MAXN 10000 int stack[MAXN];
int topc, top, t; bool judge() {
int sum = ;
for (int i=; 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 = , flag = , isNeg = ;
char pre[];
topc = top = ;
memset(pre, , sizeof (pre)); while () {
// 接收字符的代码,忽略掉空格和换行
char ch = getchar();
while ('\n'==ch || ' '==ch)
ch = getchar(); // 记录该字符前三个字符,便于判断是否为叶子
pre[] = pre[];
pre[] = pre[];
pre[] = pre[];
pre[] = ch; // 如果遇到左括弧就进栈
if ('(' == ch) {
topc++;
if (tmp) {
if (isNeg) {
tmp *= -;
isNeg = ;
}
stack[++top] = tmp;
tmp = ;
}
continue;
} // 如果遇到右括弧就出栈
if (')' == ch) {
// 如果为叶子便计算
if ('('==pre[] && ')'==pre[] && '('==pre[]) {
if (!flag)
flag = judge();
}
else if (pre[] != '('){
top--;
}
topc--;
// 如果左括弧都被匹配完说明二叉树输入完毕
if (!topc)
break;
continue;
}
if ('-' == ch)
isNeg = ;
else
tmp = tmp* + (ch-'');
} if (flag)
printf("yes\n");
else
printf("no\n");
} return ;
}
UVa 112 - Tree Summing(树的各路径求和,递归)的更多相关文章
- UVa 112 Tree Summing
题意: 计算从根到叶节点的累加值,看看是否等于指定值.是输出yes,否则no.注意叶节点判断条件是没有左右子节点. 思路: 建树过程中计算根到叶节点的sum. 注意: cin读取失败后要调用clear ...
- POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)
Tree Summing Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8132 Accepted: 1949 Desc ...
- Codeforces 618D Hamiltonian Spanning Tree(树的最小路径覆盖)
题意:给出一张完全图,所有的边的边权都是 y,现在给出图的一个生成树,将生成树上的边的边权改为 x,求一条距离最短的哈密顿路径. 先考虑x>=y的情况,那么应该尽量不走生成树上的边,如果生成树上 ...
- [转] Splay Tree(伸展树)
好久没写过了,比赛的时候就调了一个小时,差点悲剧,重新复习一下,觉得这个写的很不错.转自:here Splay Tree(伸展树) 二叉查找树(Binary Search Tree)能够支持多种动态集 ...
- 【数据结构】B-Tree, B+Tree, B*树介绍 转
[数据结构]B-Tree, B+Tree, B*树介绍 [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tre ...
- 洛谷P2633/bzoj2588 Count on a tree (主席树)
洛谷P2633/bzoj2588 Count on a tree 题目描述 给定一棵N个节点的树,每个点有一个权值,对于M个询问(u,v,k),你需要回答u xor lastans和v这两个节点间第K ...
- UVA.548 Tree(二叉树 DFS)
UVA.548 Tree(二叉树 DFS) 题意分析 给出一棵树的中序遍历和后序遍历,从所有叶子节点中找到一个使得其到根节点的权值最小.若有多个,输出叶子节点本身权值小的那个节点. 先递归建树,然后D ...
- POJ 1145 Tree Summing
Tree Summing Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 7698 Accepted: 1737 Desc ...
- easyUI之Tree(树)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...
随机推荐
- ASP.NET MVC数组模型绑定
在ASP.NET MVC中使用Razor语法可以在视图中方便地展示数组,如果要进行数组模型绑定,会遇到索引断裂问题,如下示例: <input type="text" name ...
- IEE分月表改造
IEE版本:5.1.40 需求:由于目前的IEE版本并不支持分区表,且删除历史数据效率很低,删除部分数据后空间释放方面也不理想. 现采用按月分表存放数据.这样卸载历史数据时,直接删除历史表即可. 改造 ...
- 流行趋势:25款很酷的长阴影效果 LOGO 设计
长阴影其实就是扩展了对象的投影,感觉是一种光线照射下的影子,通常采用角度为 45 度的投影,给对象添加了一份立体感.长阴影(Long Shadow)概念来自于最新非常流行的扁平化设计(Flat Des ...
- Mac常用基本命令/常用Git命令
Git地址: https://github.com/mancongiOS/command-line基本命令 目录/文件的操作 mkdir "目录名" 在当前路径下创建一个文件夹 m ...
- [SQL] Oracle基础语法
1.安装: oracle11g server 这里的口令为sys和system的密码.(10版本以前默认用户会有系统默认密码.) Oracle 11g 默认用户名和密码 oracle11g clien ...
- 用Qt写软件系列四:定制个性化系统托盘菜单
导读 一款流行的软件,往往会在功能渐趋完善的时候,通过改善交互界面来提高用户体验.毕竟,就算再牛逼的产品,躲藏在糟糕的用户界面之后总会让用户心生不满.界面设计需综合考虑审美学.心理学.设计学等多因素, ...
- math --- CSU 1554: SG Value
SG Value Problem's Link: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1554 Mean: 一个可重集合,初始为空,每 ...
- PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1
※★◆●PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1AApprriill 22001166Conte ...
- AccessHelper
代码: using System; using System.Data; using System.Configuration; using System.Data.OleDb; using ahwi ...
- 2016年5月11日摘自知乎的一些Redis大概了解
1. 知乎日报的基础数据和统计信息是用 Redis 存储的,这使得请求的平均响应时间能在 10ms 以下.其他数据仍然需要存放在另外的地方,其实完全用 Redis 也是可行的,主要的考量是内存占用.就 ...