题目: 用一种奇怪的方法表示一棵树 ( A () () ) A 是节点的权值 里面两个括号表示两个儿子 。。。 问题是否存在从根节点到叶子权值和为 一个确定值的路径。
分析: 题目很恶心 , 输入极不规范, 有种特殊情况需要注意 () 表示空树 , 不存在路径。
代码:
#define SUBMIT
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<stack>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
struct NODE{
int l,r;
int v;
}node[10000];
int sz;
char s[10000]; //保存字符串
int pos[10000]; //对应右括号位置
int len;
int bingo; // 所要找的 和
char read(){
char c=getchar();
while( !((c<='9'&&c>='0') || c=='(' || c==')' || c=='-') ) c=getchar();
return c;
}
stack<int>ST;
int input(){
while(!ST.empty()) ST.pop();
len=0;
s[len]=read(); ST.push(0);
while(!ST.empty()){
s[++len]=read();
if(s[len]=='('){
ST.push(len);
}else if(s[len]==')'){
int v=ST.top();
pos[v]=len; ST.pop(); pos[len]=0;
}else{
pos[len]=0;
}
}
s[len+1]='\0';
}
bool Build(int u,int st){
if(st>len){ return false;
}
if(s[st+1]==')') {
node[u].v=0;
node[u].r=node[u].l=0;
return false;
}
int p=st,tmp=0; p++;
bool negetive=s[p]=='-'?true:false;
if(negetive) p++;
while(s[p]<='9' && s[p]>='0') tmp=tmp*10+s[p++]-'0';
if(negetive) tmp*=-1;
node[u].v=tmp;
node[u].l=sz++; node[u].r=sz++;
if(!Build(node[u].l,p)) node[u].l=0;
p=pos[p]+1;
if(!Build(node[u].r,p)) node[u].r=0;
if(!(s[st+1]<='9' && s[st+1]>='0') && s[st+1]!='-') return false;
return true;
}
bool dfs(int u,int sum){
if(node[u].l==0 && node[u].r==0 && ( sum+node[u].v==bingo)) return true;
if(node[u].l){
if(dfs(node[u].l,sum+node[u].v)) return true;
}
if(node[u].r){
if(dfs(node[u].r,sum+node[u].v)) return true;
}
return false;
}
int main()
{
#ifndef SUBMIT
double time_start=(double)clock();
freopen("D:/output1.txt","w",stdout);
freopen("D:/input.txt","r",stdin);
#endif
//------------------------------------------------------------------------------
while(scanf("%d",&bingo)!=EOF){
memset(pos,0,sizeof(pos));
memset(node,0,sizeof(node)); sz=1;
input();
Build(0,0);
if(s[1]==')') {
puts("no"); continue;
}
if(dfs(0,0)) puts("yes");
else puts("no");
}
//------------------------------------------------------------------------------
#ifndef SUBMIT
double time_end=(double)clock();
cerr<<"\ntime: "<<(time_end-time_start)/CLOCKS_PER_SEC*1000<<"ms"<<endl;
#endif
return 0;
}