栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

UVa699

The Falling Leaves

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

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

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

#include 
#include 
#include 
#include 

using namespace std;

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

class Solution
{
public:
	Solution(const vector &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 piles;
	void construct(Node &root, const vector &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();
			construct(*root.left, input, index, pos - 1);
		}
		else index++;
		if (input.at(index) != -1) {
			root.left = make_shared();
			construct(*root.left, input, index, pos + 1);
		}
		else index++;
	}
};

int main()
{
	int cases = 0, value;
	vector 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;
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/296972.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号