下落的树叶(The Falling Leaves)

2023-05-16

The Falling Leaves
Time Limit:3000MS Memory Limit:Unknown 64bit IO Format:%lld & %llu

Submit  Status

Description

Download as PDF

Each year, fall in the North Central region is accompanied by the brilliant colors of the leaves on the trees, followed quickly by the falling leaves accumulating under the trees. If the same thing happened to binary trees, how large would the piles of leaves become?


We assume each node in a binary tree "drops" a number of leaves equal to the integer value stored in that node. We also assume that these leaves drop vertically to the ground (thankfully, there's no wind to blow them around). Finally, we assume that the nodes are positioned horizontally in such a manner that the left and right children of a node are exactly one unit to the left and one unit to the right, respectively, of their parent. Consider the following tree:

The nodes containing 5 and 6 have the same horizontal position (with different vertical positions, of course). The node containing 7 is one unit to the left of those containing 5 and 6, and the node containing 3 is one unit to their right. When the "leaves" drop from these nodes, three piles are created: the leftmost one contains 7 leaves (from the leftmost node), the next contains 11 (from the nodes containing 5 and 6), and the rightmost pile contains 3. (While it is true that only leaf nodes in a tree would logically have leaves, we ignore that in this problem.)

Input 

The input contains multiple test cases, each describing a single tree. A tree is specified by giving the value in the root node, followed by the description of the left subtree, and then the description of the right subtree. If a subtree is empty, the value -1 is supplied. Thus the tree shown above is specified as 5 7 -1 6 -1 -1 3 -1 -1. Each actual tree node contains a positive, non-zero value. The last test case is followed by a single -1 (which would otherwise represent an empty tree).

Output 

For each test case, display the case number (they are numbered sequentially, starting with 1) on a line by itself. On the next line display the number of "leaves" in each pile, from left to right, with a single space separating each value. This display must start in column 1, and will not exceed the width of an 80-character line. Follow the output for each case by a blank line. This format is illustrated in the examples below.

Sample Input 


5 7 -1 6 -1 -1 3 -1 -1
8 2 9 -1 -1 6 5 -1 -1 12 -1
-1 3 7 -1 -1 -1
-1
  

Sample Output 


Case 1:
7 11 3

Case 2:
9 7 21 15
  
【分析】

       采用递归(先序)方式输入。

用C++语言编写程序,代码如下:

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 1000;
int sum[maxn];//这里数组不能开太大否则会出现时间超限。
int mostLP = 1001;
//输入并统计一棵子树,树根水平位置为p
void build(int pos) {
	int v;
	cin >> v;
	if (v == -1) return;//空树
	sum[pos] += v;

	if (pos < mostLP)
		mostLP = pos;

	build(pos - 1);
	build(pos + 1);
}
//边读入边统计
bool init() {
	int v;
	cin >> v;
	if (v == -1) return false;
	memset(sum, 0, sizeof(sum));
	int pos = maxn / 2;//树根的水平位置
	mostLP = pos;

	sum[pos] = v;
	build(pos - 1);
	build(pos + 1);
	return true;
}

int main() {
	int kase = 0;
	while (init()) {
		//升级:加入一个变量mostLP,记录数组sum中最左边有被赋值的元素下标
		//这样做的话,就不用再去查找,递归输入的过程中就可以找到最左的位置了
		/*int p = 0;
		while (sum[p] == 0) p++;*///找最左边的叶子
		int p = mostLP;
		cout << "Case " << (++kase) << ":" << endl;
		cout << sum[p];//因为要避免行末多余空格
		for (int i = p + 1; sum[i] != 0; i++)
			cout << " " << sum[i];
		cout << endl << endl;
	}

	return 0;
}

用java语言编写程序,代码如下:

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(new BufferedInputStream(System.in));
		int kase = 0;
		final int maxn = 1000;
		int[] sum = new int[maxn];
		int mostLP;
		while((mostLP = init(input, sum)) != -1) {
			System.out.println("Case " + (++kase) + ":");
			System.out.print(sum[mostLP]);
			for(int i = mostLP + 1; sum[i] != 0; i++)
				System.out.print(" " + sum[i]);
			System.out.println('\n');
		}
	}
	
	public static int init(Scanner input, int[] sum) {
		int v = input.nextInt();
		if(v == -1) return -1;
		
		Arrays.fill(sum, 0);
		int pos = sum.length / 2;
		int[] mostLP = new int[1];
		mostLP[0] = pos;
		sum[pos] = v;
		build(input, mostLP, sum, pos - 1);
		build(input, mostLP, sum, pos + 1);
		return mostLP[0];
	}
	
	public static void build(Scanner input, int[] mostLP, int[] sum, int p) {
		int v = input.nextInt();
		if(v == -1) return;
		if(mostLP[0] > p)
			mostLP[0] = p;
		sum[p] += v;
		build(input, mostLP, sum, p - 1);
		build(input, mostLP, sum, p + 1);
	}
}




本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

下落的树叶(The Falling Leaves) 的相关文章

随机推荐

  • Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing

    原文转载自 sunny2038 的CSDN博客文章 原文地址 最近在看Java xff0c 在编译写书上一个例子时 xff0c 由于书上的代码只有一部分 xff0c 于是就自己补了一个内部类 结果编译时出现 xff1a No enclosi
  • 瑞星微开发工具下载镜像的配置方法?

    如何根据 parameter txt 建立配置表 xff1f 首先我们来看下 parameter txt 的内容 xff1a CMDLINE mtdparts 61 rk29xxnand 0x00002000 64 0x00004000 u
  • 特别困的学生(Extraordinarily Tired Students)

    Extraordinarily Tired Students Time limit 3 000 seconds When a student is too tired he can 39 t help sleeping in class e
  • 骰子涂色(Cube painting)

    Cube painting We have a machine for painting cubes It is supplied with three different colors blue red and green Each fa
  • 盒子(Box)

    Box Time limit 3 000 seconds Ivan works at a factory that produces heavy machinery He hasa simple job he knocks up woode
  • 循环小数(Repeating Decimals)

    Repeating Decimals Time limit 3 000 seconds Repeating Decimals The decimal expansion of the fraction 1 33 is wherethe is
  • 反片语(Ananagrams)

    反片语 Ananagrams 输入一些单词 xff0c 找出所有满足如下条件的单词 xff1a 该单词不能通过字母重排 xff0c 得到输入文本中的另外一个单词 在判断是否满足条件时 xff0c 字母不分大小写 xff0c 但在输出时应保留
  • 集合栈计算机(The SetStack Computer)

    The SetStack Computer Time limit 3 000 seconds 题目是这样的 xff1a 有一个专门为了集合运算而设计的 集合栈 计算机 该机器有一个初始为空的栈 xff0c 并且支持以下操作 xff1a PU
  • 代码对齐(Alignment of Code)

    Alignment of Code Time Limit 4000 2000 MS Java Others Memory Limit 32768 32768 K Java Others Total Submission s 958 Acce
  • Ducci序列(Ducci Sequence)

    Ducci Sequence Time limit 3 000 seconds A Ducci sequence is a sequence of n tuples of integers Given an n tuple of integ
  • 卡片游戏(Throwing cards away I)

    Problem B Throwing cards away I Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at
  • 交换学生(Foreign Exchange)

    Problem E Foreign Exchange Input standard input Output standard output Time Limit 1 second Your non profit organization
  • CAN通信物理容错测试checklist

    CAN通信物理容错测试checklist 工作项目中 xff0c 我们有时有些产品CAN总线功能 xff0c 一般情况下我们必须要满足以下几种状况的测试项才算符合要求 一 CAN H与CAN L短路 判定标准 xff1a 短接故障发生后 x
  • 对称轴(Symmetry)

    Symmetry Time limit 3 000 seconds The figure shown on the left is left right symmetric as it is possible to fold the she
  • 打印队列(Printer Queue)

    Printer Queue Time limit 3 000 seconds 分析 首先记录所求时间它在队列中的位置 xff0c 用一个队列存储这些任务的优先级 xff0c 同时也创建一个队列存储对应任务一开始的位置 xff0c 那么当我们
  • 更新字典(Updating a Dictionary)

    Updating a Dictionary Time Limit 1000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description In th
  • 铁轨(Rails)

    Rails Time limit 3 000 seconds Rails There is a famous railway station in PopPush City Country there is incredibly hilly
  • 矩阵链乘(Matrix Chain Multiplication)

    Matrix Chain Multiplication Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description
  • 天平(Not so Mobile)

    Not so Mobile Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Before being
  • 下落的树叶(The Falling Leaves)

    The Falling Leaves Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Each yea