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
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; }
相关文章推荐
- 数据结构 uva 112-Tree Summing
- uva oj 112 - Tree Summing
- uva_112_Tree Summing
- UVa 112 - Tree Summing
- UVa 112 - Tree Summing 二叉树构造, 二叉树路径和
- uva 112 Tree Summing
- UVA 112 & POJ 1145 Tree Summing(数据结构,二叉树,栈)
- UVa 112 - Tree Summing
- uva112 - Tree Summing
- UVA - 112 Tree Summing
- UVa 112 - Tree Summing
- UVA - 112 - Tree Summing (数的求和!栈的应用!)
- uva-112 Tree Summing
- Uva 112 Tree Summing
- uva 112 Tree Summing
- UVa 112 Tree Summing (scanf()去空格&递归&二叉树遍历)
- UVA112-Tree Summing
- uva 112 Tree Summing
- UVA_112_Tree Summing
- uva_112-Tree Summing