算法竞赛入门经典 例题6-10

UVa699

The Falling Leaves

定义二叉树中左子节点距父节点左边一个单位的水平距离,右子节点距父节点右边一个单位的水平距离,求相同水平坐标上的节点值的和。

构建树的方式和前面几道题类似,求解的方式也比较简单,这道题中麻烦地方在于没有办法根据输入数据将测试样例分开,需要一次性全部读入才可以。

最近总是不信邪,认为题目中的两个输出之间有一个空行同一行中的输出用空格分开可以理解为最后一个输出后面也可以有空格和换行,结果收获了一堆Presentation error 😦😦😦

#include <iostream>
#include <memory>
#include <map>
#include <vector>

using namespace std;

struct Node
{
	int value, positon;
	shared_ptr<Node> left, right;
};

class Solution
{
public:
	Solution(const vector<int> &input, size_t &index)
	{
		construct(tree, input, index, 0);
	}
	void output(ostream &os)
	{
		os << piles.begin()->second;
		for (auto iter = ++piles.begin(); iter != piles.end(); iter++)
		{
			os << ' ' << iter->second;
		}
		os << endl;
	}
private:
	Node tree;
	map<int, int> piles;
	void construct(Node &root, const vector<int> &input, size_t &index, int pos)
	{
		root.value = input.at(index++);
		root.positon = pos;
		piles[pos] += root.value;
		if (input.at(index) != -1) {
			root.left = make_shared<Node>();
			construct(*root.left, input, index, pos - 1);
		}
		else index++;
		if (input.at(index) != -1) {
			root.left = make_shared<Node>();
			construct(*root.left, input, index, pos + 1);
		}
		else index++;
	}
};

int main()
{
	int cases = 0, value;
	vector<int> input;
	while (cin >> value) {
		input.push_back(value);
	}
	size_t index = 0;
	while (input[index] != -1) {
		Solution solution(input, index);
		cout << "Case " << ++cases << ":" << endl;
		solution.output(cout);
		cout << endl;
	}
	return 0;
}
/*
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
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值