uva_112 - Tree Summing (树的求和)

UVA 112 & POJ 1145 Tree Summing(数据结构,二叉树,栈) http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=48 http://poj.org/problem?id=1145 阅读详情

 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.

picture25

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

 
empty tree 		 ::= 		 ()

tree ::= empty tree tex2html_wrap_inline118 (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 pairI,T (I represents the integer, T represents the tree) the output is the stringyes if there is a root-to-leaf path in T whose sum is I andno 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

	这道题给你一个值n和一棵整数二叉树的先序遍历的形式 ( value ( left subtree) ( right subtree))的形式,判断是否存在某条路径的节点和等于n。我用的是最笨最麻烦的方法,先根据表达形式复原二叉树,再遍历一遍各个路径。
	
#include <iostream>
#include <stack>
#include <cstdio>
#include <cmath>

using namespace std;

int n;

struct Node
{
   int data;
   Node * left, * right;
};

typedef Node * Position;



Position & buildTree( char * str, int s, int e)
{
    Position root = NULL;
    if( str[s+1] == ')')  return root;

    root = new Node;
    root->data = 0;


    stack<int> st;
    int sign = 0;
    if( str[s+1] == '-')  { sign = 1; s++;}
    int i;
    for( i = s+1; (str[i]<='9' && str[i]>='0'); i++)
        st.push( str[i]-'0');

    int cnt = 0;
    while( !st.empty()){
        root->data += pow( 10, cnt++)*st.top();
        st.pop();
    }
    if( sign) root->data *=-1;



    int ls = i;
    stack<char> chS;
    chS.push( str[i]);
    do{
        i++;
        if( str[i] == '(') chS.push( str[i]);
        if( str[i] == ')') chS.pop();
    }while( !chS.empty());

    root->left = buildTree( str, ls, i);
    root->right = buildTree( str, i+1, e-1);

    return root;
}



int getSum( int sum, const Position & t)
{
    if( !t->left && !t->right) return sum == n;


    bool ans = false;
    if( t->left) ans = getSum( sum+t->left->data, t->left);
    if( ans) return ans;
    if( t->right) ans = getSum( sum+t->right->data, t->right);

    return ans;
}

void makeEmpty( const Position & t)
{
    if( !t) return;
    makeEmpty( t->left);
    makeEmpty( t->right);
    delete t;
}


char str[50000];

int main()
{

    while( cin >> n){
        int i = 0;
        int leftPar = 0,rightPar = 0;
        char ch;
        while( scanf("%c", &ch)){
            if( ch == '(') leftPar++;
            if( ch == ')') rightPar++;
            if( ch != '\n' && ch != ' ') str[i++] = ch;
            if( leftPar == rightPar && leftPar) break;
        }
        str[i] = 0;

        Position root = NULL;
        root = buildTree( str, 0, i-1);


        if( !root) cout << "no" << endl;
        else if( getSum( root->data, root)) cout << "yes" << endl;
        else cout << "no" << endl;

        makeEmpty( root);
    }

    return 0;
}

   网上看高手的解题报告,发现可以用递归边输入边处理,代码又快又短-.- 还看到了有cin.clear()这种好东西

#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;
}
代码来自:http://www.cnblogs.com/devymex/archive/2010/08/10/1796854.html
光学系统设计:波段、光源、光纤与探测器匹配指南 在光学测量和光纤通信系统中,波段、光源、光纤和探测器的匹配关系是系统设计的核心基础。波段指电磁波谱中的特定波长范围,光源负责产生特定波长的光信号,光纤作为传输介质需要与波长匹配以降低损耗,探测器则负责将光信号转换为电信号。理解各组件的光谱特性对于系统性能至关重要,例如在850nm短波长多模光纤系统中,VCSEL激光器与PIN光电二极管的组合能提供最佳性价比。典型应用场景包括生物医学成像、光纤通信和气体传感,其中光谱重叠优化、模场直径匹配和偏振特性协调是关键技术要点。通过实测数据对比不同组合的传输性能,可以为 阅读详情

相关推荐

Wider Face+YOLOV7人脸检测

使用Wider Face数据集训练YOLOV7

chen_znn的博客 8408

Tree Summing (二叉搜索树的输入处理)

    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 ...

自渡的博客 586

U盘 未知USB设备 设定地址失败 由于该设备有问题Windows 已将其停止(代码 43) 终极解决方案(做过系统装机盘而无法解决的必看)

U盘由于该设备有问题Windows 已将其停止(代码 43) 终极解决方案 我们在使用U盘的时候偶尔会碰到下列情况 一般是因为传输数据的过程中,死机或未响应直接断点或拔掉设备导致的,U盘再次插上之后出现设定地址失败。无法再次读取设备的数据。 解决方案: 首先请确认出现该情况不是因为你摔了U盘或接口处产生断裂这种物理损伤导致的!!! 首先请确认出现该情况不是因为你摔了U盘或接口处产生断裂这种物理损...

qq_39123987的博客 13万+

POJ 1145 Tree Summing(树)

POJ 1145 Tree Summing 题意: Lisp语言中表达一颗树是用叫做S-expressions的方式来表达的,S-expressions有如下形式: empty tree ::= () tree ::= empty tree (integer tree tree) 比如下图这颗树用S-expressions表达为: (5 (4 (11 (7 () ()) (2 () ...

ha_ha_ha233的博客 542

一个基于fluent超声振动仿真算例分析(含有UDF的编写设定)

一个基于Fluent的超声防堵算例

Lvyou2008的博客 2513

探索robotics-toolbox-python:从基础安装到高级机器人运动学应用

本文详细介绍了robotics-toolbox-python工具箱,从基础安装、环境配置到机器人运动学与动力学的核心应用。通过D-H参数、URDF导入和内置模型三种方式快速构建机器人模型,并演示了正逆运动学计算、关节空间与任务空间轨迹规划以及三维可视化仿真。该工具箱极大地简化了机器人算法开发流程,是进行机器人学研究和应用实践的强大工具。

i1j2k的博客 496

2649: Tree Summing

2649: Tree Summing

qq_34351732的博客 338

【转载】参数估计(Parameter Estimation):频率学派(最大似然估计MLE、最大后验估计MAP)与贝叶斯学派(贝叶斯估计BPE)

基础 频率学派与贝叶斯学派 http://www.douban.com/group/topic/16719644/ http://www.zhihu.com/question/20587681 最大似然估计(Maximum likelihood estimation,MLE) http://baike.baidu.com/view/1918804.htm http://baike.baidu.co

影 的专栏 3413

UVa 112 - Tree Summing解题报告

题意: 题目要求很简单,意思是要构造一颗二叉树,然后求出所有根结点到叶结点的路径上的数字之和,如果有一个是和题目所给的一样,那么输出yes,否则no 左括号‘(' 表示新建一个子结点, 优先建立左儿子,如果左儿子建立过了,则建立右儿子。 右括号表示退回父结点。如果一对括号内是空的,表示这个结点 也是空的。 思路: 输入比较复杂, 有括号,有数字,又

Yonah潇的专栏 891

Obsidian跨设备同步实战:阿里云OSS与Remotely Save插件配置指南

本文详细介绍了如何利用阿里云OSS对象存储与Remotely Save插件,为Obsidian笔记软件搭建一个低成本、高可靠性的私有化多端同步方案。从创建OSS Bucket、配置CORS规则、生成子账户密钥,到插件安装与多设备同步策略,提供了完整的实战配置指南,有效解决Obsidian用户的跨设备同步痛点。

qsc901234567的博客 1284

吹气压力传感器US6310 US6330调试

更换压力传感器, 从US6310 更换为US6330。 6310有一个准备好引脚,AD转换完成后会给MCU一个脉冲 而6330就没有这个功能,6330这个引脚是用来选择SPI还是I2C接口的。(6330没有复位引脚,内部有POR功能) 因此在实现上是有根本区别的, 其它方面使用的命令也不一样, 6310 A8 A9两条命令,一个命令模块醒来,一个命令模块休眠, 6330只有一条命令AA, 命令模块开始转换。 针对这2个模块作为2种处理方法, 1. 6310,可以设置一...

明天乌儿会歌唱 2024

Problem B: Tree Summing

【代码】Problem B: Tree Summing。

m0_73232096的博客 460

AI上推荐 之 隐语义模型(LFM)和矩阵分解(MF)

1. 前言 随着信息技术和互联网的发展, 我们已经步入了一个信息过载的时代,这个时代,无论是信息消费者还是信息生产者都遇到了很大的挑战: 信息消费者:如何从大量的信息中找到自己感兴趣的信息? 信息生产者:如何让自己生产的信息脱颖而出, 受到广大用户的关注? 为了解决这个矛盾, 推荐系统应时而生, 并飞速前进,在用户和信息之间架起了一道桥梁,一方面帮助用户发现对自己有价值的信息, 一方面让信息能够展现在对它感兴趣的用户前面。 推荐系统近几年有了深度学习的助推发展之势迅猛, 从前深度学习的传统推荐模型(协

Miracle8070 1万+

UVa OJ 112 - Tree Summing (树的求和)

Time limit: 3.000 seconds限时:3.000秒 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 ...

weixin_30439067的博客 305

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

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 o...

weixin_30367169的博客 139

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

UVa 112 Tree Summing

本文探讨了如何解析LISP S-表达式表示的二叉树,并判断是否存在根到叶子的路径和等于给定目标值。通过递归解析表达式构建二叉树,采用深度优先搜索在构建过程中累加路径和,到达叶子节点时进行比较。处理了空树、负数和零等边界情况,时间复杂度为O(N)。参考代码展示了完整的解析和搜索过程,通过递归匹配S-表达式的嵌套结构,实现高效求解。

寂静山林 780

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

uva 112 Tree Summing

uva 112 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 fun

总有那么一群人喜欢盯着我的博客看,估计这是他们见过最长的博客名,我必须得告诉他们博客名最长可以写多长 894

uva112 Tree Summing(二叉树 + 栈)

题意:LISP 列表语言实现二叉树, 构树方式对照图就可知道,  叶子后面都有两个()。 给定一个数target, 求此树中是否有一条路径(从root到叶子), 它上面的结点总和等于target, 如果存在 输出yes, 否则输出no。 思路:这道题可以不用建树。只要读到叶子结点的时候, 把这条路的sum 跟 target比较, 相等就ok = true。 如何读? 读到( 入栈staS

MistKafka的专栏 1184

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 th

不慌不忙、不急不躁 2470

Uva 112 Tree Summing

Uva 112 Tree SummingBackground 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 d

long-long-ago 506

UVA 112 - Tree Summing(栈)

又是一道让我心碎的题。UVA上提交了10几次都错了,在北大上又过了。用栈做的,在处理输入和判断括号上感觉还蛮良好的。 #include #include #define MAXN 10000 int stack[MAXN]; int topc, top, t; bool judge() { int sum = 0; for (int i=1; i<=to

zcube的技术博客 2744

UVA 112 Tree Summing

题目:   用一种奇怪的方法表示一棵树   ( A () () )   A 是节点的权值  里面两个括号表示两个儿子  。。。     问题是否存在从根节点到叶子权值和为 一个确定值的路径。 分析:  题目很恶心  ,   输入极不规范,   有种特殊情况需要注意  () 表示空树 ,   不存在路径。 代码: #define SUBMIT #include

u011276914的专栏 686

UVa 112 - Tree Summing

树. 题意很简单, 让你

一只冰熊 944

UVa Problem 112 - Tree Summing

// UVa Problem 112 - Tree Summing // Verdict: Accepted // Submission Date: 2011-11-26 // UVa Run Time: 0.304s // // 版权所有(C)2011,邱秋。metaphysis # yeah dot net // // [解题方法] // 本题可以归结为数据结构问题。 // // 使用链表来表

寂静山林 1790

UVA 112-Tree Summing

UVA 112-Tree Summing题目大意:输入一个数x,求在树上是否有路径的数之和与x相同解题思路:第一次做这种题目,一开始没思路,看了大神代码,才学到新知识,递归求解,当左右子树为空时返回#include <stdio.h> #include <iostream> #include <string.h> using namespace std; char get() { char

ZeroLH00的博客 639

uva 112 tree summing

这题应该可以用栈结构直接

废弃。。 505
上一篇: uva_101 - The Blocks Problem
下一篇: uva_ 548-Tree
HuanTongH
博客等级 码龄12年 7粉丝 110原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值