The Falling Leaves, UVa 699 algorithm competition entry classic example questions 6-10

topic

link

Click here to jump to the topic

enter

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

Output

Case 1:
7 11 3
Case 2:
9 7 21 15

AC code on the book

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
const int maxn = 80;
int sum[maxn];

//输入并统计一棵子树,树根水平位置为p 
void build(int p) {
    
    
	int v; cin >> v;
	if (v == -1) return; //空树 
	sum[p] += v;//同一个位置的权值直接加和
	build(p - 1); build(p + 1);
}
//边读入边统计 
bool init() {
    
    
	int v; cin >> v;
	if (v == -1) return false;//输入结束
	memset(sum, 0, sizeof(sum));//清空数组
	int pos = maxn / 2; //树根的水平位置 
	sum[pos] = v;
	build(pos - 1); build(pos + 1);//先完成全部左子树,再完成右子树
}
int main() {
    
    
	int kase = 0;
	while (init()) {
    
    
		int p = 0;
		while (sum[p] == 0) p++; //找最左边的叶子 
		cout << "Case " << ++kase << ":\n" << sum[p++];//因为要避免行末多余空格 
		while (sum[p] != 0) cout << " " << sum[p++];
		cout << "\n\n";
	}
	return 0;
}

postscript

There are still two sample questions to learn today. First, throw up the code and analysis. As for the rest, let
’s talk about it when I have
time. -Konjac’s sixth blog January 22, 2020 19:12

Guess you like

Origin blog.csdn.net/m0_52494226/article/details/112997742