題意:
給一個數a和一棵帶權樹T,判斷T根到葉子的若干路徑的權和中是否有和a相等的。
分析:
棧用來表達式求值有兩種辦法,一是將表達式轉爲後序再求值,二是利用單調符號棧一次掃描。單調符號棧一次掃描法求值時維護單調符號棧(棧中總是優先級低的符號在下,‘(’在棧外優先級最高,棧中優先級最低,‘)’在棧外優先級最低,不可能出現在棧中)。先搞清楚表達式求值的單調符號棧一次掃描法這題就容易了,在這題中用棧模擬樹的前序遍歷。
代碼:
//poj 1145
//sep9
#include <iostream>
#include <stack>
using namespace std;
bool isChar(char ch)
{
return ch=='('||ch==')'||(ch>='0'&&ch<='9')||ch=='-';
}
int main()
{
int tot;
char ch;
while(scanf("%d",&tot)==1){
stack<int> nums,states;
int cnt=0,cur=0;
bool read_enable=true;
bool find=false;
bool flag=false;
while(1){
if(read_enable)
while((ch=getchar())&&!isChar(ch));
if(ch=='('){
++cnt;
read_enable=true;
continue;
}
if(ch==')'){
--cnt;
if(!states.empty())
++states.top();
if(!states.empty()&&states.top()==3){
if(flag&&cur==tot) find=true;
flag=false;
cur-=nums.top();
nums.pop();
states.pop();
if(!states.empty())
++states.top();
}
if(cnt==0)
break;
read_enable=true;
continue;
}
int neg=1;
if(ch=='-'){
ch=getchar();
neg=-1;
}
int tmp=0;
do{
int a=ch-'0';
tmp=10*tmp+a;
}while((ch=getchar())&&ch>='0'&&ch<='9');
tmp*=neg;
cur+=tmp;
flag=true;
nums.push(tmp);
states.push(0);
if(ch=='(')
read_enable=false;
else
read_enable=true;
}
printf("%s\n",find?"yes":"no");
}
return 0;
}