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;
}

你可能感兴趣的:(tree,uva,Backtrack)