代码长,,,其实解题不用这么麻烦的。。就当练习二叉树了QAQ。
#include <iostream>
#include <string>
using namespace std;
struct tree
{
int data;
tree *left,*right;
};
void clr(string a)
{
for(string::iterator it = a.begin();it != a.end();++it)
if ( *it != '(' && *it != ')' && (*it < 48 || *it > 57) && *it != '-')
a.erase(it);
}
bool match(string a)
{
int c = 0,b = 0;
for(string::iterator it = a.begin();it != a.end();++it)
{
if(*it == '(')
c++;
if(*it == ')')
b++;
}
if(c != b || a.size() == 0)
return true;
else return false;
}
void del(tree* &go)
{
if(go != NULL)
{
if(go->left != NULL)
del(go->left);
if(go->right != NULL)
del(go->right);
delete go;
}
go = NULL;
}
unsigned int m = 0;
string trees = "";
void ft(tree* go,int all,int num,int& flag)
{
if(m+1 < trees.size() && trees[m] == '(' && trees[m+1] != ')')
{
tree* make = new tree;
go->left = make;
int u = m+1,sum = 0,dis = 0;
if(trees[m+1] == '-') {dis = 1;m ++;u++;}
while(trees[u] > 47 && trees[u] < 58)
{
sum *= 10;
sum += trees[u] - 48;
u++;
m = u - 2;
}
if(dis == 1) sum = -sum;
make->data = sum;
sum += all;
m += 2;
ft(go->left,sum,num,flag);
}else
{
go->left = NULL;
m += 2;
}
if(m+1 < trees.size() && trees[m] == '(' && trees[m+1] != ')')
{
tree* make = new tree;
go->right = make;
int u = m+1,sum = 0,dis = 0;
if(trees[m+1] == '-') {dis = 1;m ++;u++;}
while(trees[u] > 47 && trees[u] < 58)
{
sum *= 10;
sum += trees[u] - 48;
u++;
m = u - 2;
}
if(dis == 1) sum = -sum;
make->data = sum;
sum += all;
m += 2;
ft(go->right,sum,num,flag);
}else
{
go->right = NULL;
m += 2;
}
m += 1;
if(go->left == NULL && go->right == NULL && all == num)
flag = 1;
}
int main()
{
int num;
while(cin >> num)
{
string mu;
trees = "";
m = 0;
int flag = 0;
tree forest,*go = &forest;
go->left = go->right = NULL;
while(match(trees))
{
cin >> mu;
trees += mu;
}
clr(trees);
ft(go,0,num,flag);
del(go->left);
if(flag == 1)
cout << "yes" << endl;
else cout << "no" << endl;
}
return 0;
}