UVA_112_Tree Summing

#include<iostream>
#include<sstream>
#include<vector>
#include<string>
#include<stack>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::stringstream;
using std::stack;
const int MAX = 2147483647;
typedef struct NodeType
{
	int value;
	NodeType *pre = nullptr;
	NodeType *next = nullptr;
	bool flag = true;
}NodeType, *Node;
int result(Node p)
{
	if (p)
	{
		return p->value + result(p->pre);
	}
	else
	{
		return 0;
	}
}
bool judge(stack<Node>&leaf, const int &sum)
{
	while (!leaf.empty())
	{
		auto p = leaf.top(); leaf.pop();
		if (sum == result(p))
		{
			return true;
		}
	}
	return false;
}
void scan(stack<Node>&leaf)
{
	stack<char>bracket;
	stack<Node>value;
	char ch;
	int result = MAX;
	int sign = 1;
input:    while (cin >> ch)
{
	if (ch == '-')
	{
		sign = -1;
	}
	else if (ch == '(' || ch == ')')
	{
		if (ch == '(')
		{
			if (!value.empty())
			{
				if (result != MAX)
				{
					//value.emplace(nullptr,result,value.top(),true);
					auto p = new NodeType;
					p->value = result;
					p->pre = value.top();
					p->next = nullptr;
					p->flag = true;
					value.top()->next = p;
					value.push(p);
					result = MAX;
					sign = 1;
				}
			}
			else
			{
				if (result != MAX)
				{
					auto p = new NodeType;
					p->value = result;
					p->pre = nullptr;
					p->next = nullptr;
					p->flag = true;
					value.push(p);
					result = MAX;
					sign = 1;
				}
			}
			bracket.push(ch);
		}
		else
		{
			bracket.pop();
			if (bracket.empty() && value.empty())
			{
				break;
			}
			if (value.top()->flag)
			{
				value.top()->flag = false;
			}
			else
			{
				if (!value.top()->next)
				{
					leaf.push(value.top());
				}
				value.pop();
			}
		}
	}
	//如果是数字
	else
	{
		if (result == MAX)
		{
			result = 0;
		}
		result *= 10;
		if (sign > 0)
		{
			result += ch - '0';
		}
		else
		{
			result -= ch - '0';
		}
	}
}
}
void print(stack<Node>&leaf, const int &sum)
{
	if (judge(leaf, sum))
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}
}
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int sum;
	while (cin >> sum)
	{
		stack<Node> leaf;
		scan(leaf);
		print(leaf, sum);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值