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
1 #include <iostream> 2 #include <stack> 3 #include <cmath> 4 using namespace std; 5 6 int sum(stack<int> s){ 7 int result = 0; 8 while (!s.empty()){ 9 result += s.top(); 10 s.pop(); 11 } 12 return result; 13 } 14 15 int main(int argc, char *argv[]){ 16 17 stack<int> num; 18 int test_num, link_paren = 0; 19 char ch = ' '; 20 bool bMatch = false, bLeftParen = false, 21 bClear = false, bNumber = false; 22 23 cin >> test_num; 24 while (ch != '#'){ 25 if (bClear) 26 bClear = false; 27 else if (bNumber) 28 bNumber = false; 29 else 30 cin >> ch; 31 32 if (ch == ')') { 33 if (bLeftParen && link_paren == 2){ 34 bLeftParen = false; 35 link_paren = 0; 36 int check = sum(num); 37 if (check == test_num){ 38 bMatch = true; 39 break; 40 } 41 } 42 else if (bLeftParen && link_paren == 0){ 43 link_paren = 2; 44 } 45 else { 46 // clear the stacks 47 link_paren = 0; 48 num.pop(); 49 while (cin >> ch && ch == ')'){ 50 num.pop(); 51 } 52 bClear = true; 53 // The last ch is '(' 54 } 55 } 56 else if (ch == '(') { 57 bLeftParen = true; 58 } 59 else { 60 bool negative = false; 61 if (ch == '-'){ 62 negative = true; 63 cin >> ch; 64 } 65 int integer = ch - '0', number = 0; 66 while (integer <= 9 && integer >= 0){ 67 cin >> ch; 68 number = number*10 + integer; 69 integer = ch - '0'; 70 } 71 72 if (negative) 73 number *= -1; 74 num.push(number); 75 bNumber = true; 76 // ch is '(' 77 } 78 } 79 80 if (bMatch) 81 cout << "Yes" << endl; 82 else 83 cout << "No" << endl; 84 85 return 0; 86 }