您的位置:首页 > 其它

UVA 112 - Tree Summing

2013-01-19 12:31 471 查看
Algorithm:

one stack for numbers: num_stack

if leaf node is found:

  calculate the sum of the numbers in the num_stack

  if matched:

    return true

  else:

    pop out the numbers in num_stack according to the number of ')'

else:

  push number into num_stack    

View Code

#include <iostream>
#include <stack>
#include <cmath>
using namespace std;

int sum(stack<int> s){
int result = 0;
while (!s.empty()){
result += s.top();
s.pop();
}
return result;
}

int main(int argc, char *argv[]){

stack<int> num;
int test_num, link_paren = 0;
char ch = ' ';
bool bMatch = false, bLeftParen = false,
bClear = false, bNumber = false;

cin >> test_num;
while (ch != '#'){
if (bClear)
bClear = false;
else if (bNumber)
bNumber = false;
else
cin >> ch;

if (ch == ')') {
if (bLeftParen && link_paren == 2){
bLeftParen = false;
link_paren = 0;
int check = sum(num);
if (check == test_num){
bMatch = true;
break;
}
}
else if (bLeftParen && link_paren == 0){
link_paren = 2;
}
else {
// clear the stacks
link_paren = 0;
num.pop();
while (cin >> ch && ch == ')'){
num.pop();
}
bClear = true;
// The last ch is '('
}
}
else if (ch == '(') {
bLeftParen = true;
}
else {
bool negative = false;
if (ch == '-'){
negative = true;
cin >> ch;
}
int integer = ch - '0', number = 0;
while (integer <= 9 && integer >= 0){
cin >> ch;
number = number*10 + integer;
integer = ch - '0';
}

if (negative)
number *= -1;
num.push(number);
bNumber = true;
// ch is '('
}
}

if (bMatch)
cout << "Yes" << endl;
else
cout << "No" << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: