题目的意思就是先给出一个数,,然后给出的一颗树,看看这棵树从根到叶子,有没有一条路和等于这个数。。
这道题读入也是一个坑!充满空格和回车。
我首先是一个个字符读,如果读到数字,左括号,右括号,和符号,就存进str字符串。。当读到左右括号数量一样时结束。。
就把读入处理成正常的一段了。。
这道题本来一直想想着建颗树,然后遍历,后来发现根本不用,因为输入本身就是树的中序遍历。。
所以直接开始处理这一串,如果读到两个空括号,就说明读到叶子了,这时候把前面全部的数字加起来就得到这条路的和;
关于上面说到的这个思路,我是这么做的。用一个栈来存左括号,再用一栈来存 数字和(注意是数字和,这样比较的时候只要和栈顶比较,而且第一条路不是,要退回去,算第二条时不用重复计算,应为存的就是根到某一节点的和。) (当然中间需要一步把字符串数字转为整型的数字,做法就不说了)
如果读到右括号,并且判断出了左括号比数字多两个的时候,就把目标数字和栈顶比较一下是不是,。然后读到右括号还要把栈顶数字去掉,这样这条路不行,就能退回去算另一条路,因为右括号数量和树的的深度是相关的。。
AC代码:
#include<iostream>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<cmath>
using namespace std;
int main () {
int tar;
char ch;
string str ;
stack<char> num;
stack<int> sum;
stack<char> sign;
int lef = 0;
int rig = 0;
int res = false;
while (scanf("%d",&tar) != EOF) {
getchar();
str = "";
while(1) {
ch = getchar();
if (ch == '(' || ch == ')' || ch == '-' || (ch >= '0' && ch <= '9')) {
str += ch;
if (ch == '(')
lef++;
if (ch == ')')
rig++;
if(rig == lef)
break;
}
}
int count = 0;
for (int i = 0 ; i < str.size() ;i++) {
if (str[i] == '(') {
sign.push(ch);
if (!num.empty()) {
int flag = 0;
int temp = 0;
while (!num.empty() && num.top() != '-') {
temp += (num.top() - 48) * pow(10,flag);
flag++;
num.pop();
}
if (!num.empty()) {
temp = -temp;
num.pop();
}
if (!sum.empty())
temp += sum.top();
sum.push(temp);
}
}
if ( (str[i] >= '0' && str[i] <= '9') || str[i] == '-' ) {
num.push(str[i]);
count = 0;
}
if (str[i] == ')') {
if (sum.size() != sign.size()) {
count++;
if (!sum.empty() && count == 2 && sum.top() == tar) {
res = true;
}
}
else
sum.pop();
sign.pop();
}
}
if (res == true)
cout << "yes" <<endl;
else
cout << "no" << endl;
res = false;
}
return 0;
}