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


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

Source

Root :: Competitive Programming 3: The New Lower Bound of Programming Contests (Steven & Felix Halim) :: Graph :: Special Graphs (Others) :: Tree

Root :: Competitive Programming 2: This increases the lower bound of Programming Contests. Again (Steven & Felix Halim) :: Graph :: Special Graphs (Others) :: Tree

Root :: Competitive Programming: Increasing the Lower Bound of Programming Contests (Steven & Felix Halim) :: Chapter 4. Graph :: Special
Graph - Tree

Root :: AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 2. Data Structures :: Binary Trees

我尼玛!这题真做的我整个人都不好了........

首先数据很坑!!

输入:

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

0 ()

5 (5 () ())

5 ( 5 () () )

5 (1 (3 () ()) (4 () ()))

5 (18 ( - 13 ( ) ( ))())

0 (1 ()(-2 () (1()()) ) )

2 (1 () (1 () (1 () () ) ) )

10 (5 () (5 () (5 () (5 () (4 () () ) ) ) ) )

10 (5 () (5 () (5 () (5 ( 3 () () ) (4 () () ) ) ) ) )

20 (5 () (5 () (5 () (5 () (4 () () ) ) ) ) )

输出:

yes

no

yes

no

no

yes

yes

yes

yes

yes

no

no

no

no

居然尼玛有负号!!

还居然负号和数字之间有空格!!

我差点笑出声啊!!

哈哈哈哈哈%>_<%!!

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;

int main()
{
	int n;
	char a[300];
	while(scanf("%d", &n) != EOF)
	{
		stack<int> snum;
		stack<char> sch;
		int sum = 0, flag = 0;
		int iswei = 0;  //判断是否到了叶子节点
		gets(a);
		while(1)
		{
			for(int i=0; a[i] != '\0'; i++)
			{
				if( (a[i] <= '9' && a[i] >= '0') || a[i] == '-')
				{
					iswei = 0;
					int t = 0, f = 0;
					if(a[i] == '-')
					{
						while(a[i]>'9' || a[i] < '0') i++;
						f = 1;
					}
					while(a[i] <= '9' && a[i] >='0')
					{
						t = t*10 + a[i]-'0';
						i++;
					}
					i--;
					if(f) t = -t;
					sum += t;
					snum.push(t);
				}
				else if(a[i] == '(')
				{
					iswei++;
					sch.push(a[i]);
				}
				else if(a[i] == ')')
				{
					//printf("%d %d\n", sch.size(), snum.size());
					if(sch.size() == snum.size())
					{
						if(iswei == 2 && sum == n)  flag = 1;  //之前在这里就直接break了,导致后面没输入进去,纠结我好久
						sum -= snum.top();
						snum.pop();
						iswei = 0;
					}
					sch.pop();
					//printf("%d\n", sum);
				}
			}
			if(sch.empty()) break;   //当所有()都匹配好了后即栈为空就说明树输出完毕,然后就跳出循环
			else
			{
				gets(a);
			}
		}
		if(flag == 1) printf("yes\n");
		else printf("no\n");
	}
	return 0;
}

另附大牛的代码(Orz...):

#include<iostream>
using namespace std;
bool ok;
bool tree_sum(int n,int sum)
{
    int v;
    char ch;
    cin>>ch;
    if(!((cin>>v)==0))
    {
        n+=v;
        bool t=tree_sum(n,sum)|tree_sum(n,sum);
        if(!ok&&!t)
            ok=(n==sum);
        cin>>ch;
        return true;
    }
    else
    {
        cin.clear();
        cin>>ch;
        return false;
    }
}
int main()
{
    // freopen("f:\\out.txt", "w", stdout);
    int sum;
    while(cin>>sum)
    {
        ok=false;
        tree_sum(0,sum);
        cout<<(ok?"yes":"no")<<endl;
    }
    return 0;
}
时间: 2024-10-25 11:29:59

UVA - 112 - Tree Summing (数的求和!栈的应用!)的相关文章

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

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

uva 10410 - Tree Reconstruction(栈)

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

Tree Summing[UVA-112]

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

uva 11290 - Gangs(卡特兰数)

题目链接:uva 11290 - Gangs 题目大意:给出n和k,表示要构造一个长度为2*n-2的字符串,OG序列为k的字符串(类似于出栈入栈). 如果字符s2先回到原点(即栈空),那么s2 OG s1 如果s1和s2同事回答原点,那么忽略头尾的ES进行比较 如果s1和s2的前t个相同,扣掉前t个字符考虑 解题思路:出栈入栈的个数是卡特兰数,每次考虑两个部分 Sstr1Estr2. #include <cstdio> #include <cstring> #include <

[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

UVa 1583 Digit Generator(数)

For a positive integer N , the digit-sum of N is defined as the sum of N itself and its digits. When M is the digitsum of N , we call N a generator of M . For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of