交啦好几次运行错误,原来是数组开小了,快哭死了,本体没别的难点,就是建一个简单的二叉树,然后用递归取值就行了,如果学的比较好的话可以不建树就能做
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
int N,flag;
struct p
{
int pri;
p *left,*right;
} ;
p *root;
void sum(p *y,int n)
{
if(y!=NULL)
{
if(y->left==NULL&&y->right==NULL)
{
n+=y->pri;
if(n==N)flag=1;
}
if(y->left!=NULL)
sum(y->left,n+y->pri);
if(y->right!=NULL)
sum(y->right,n+y->pri);
}
}
int main()
{
//freopen("a.txt","r",stdin);
int i,count1,count2,count,j,k;
char s,str[10100];
while(scanf("%d",&N)!=EOF)
{
stack<p *> v;
memset(str,0,sizeof(str));
count1=count2=count=0;
while(1)
{
scanf("%c",&s);
if(s=='(')count1++;
else if(s==')')count2++;
if(s=='('||s==')'||s=='-'||(s>='0'&&s<='9'))
str[count++]=s;
if(count1==count2&&count1!=0)break;
}
getchar();
for(i=count-1; i>=0; i--)
{
if(str[i]==')'&&str[i-1]=='(')
{
root=new p;
root->left=root->right=NULL;
root->pri=0;
root=NULL;
v.push(root);
i--;
}
else if(str[i]>='0'&&str[i]<='9')
{
j=i;
count1=count2=0;
for(i=i-1;; i--)
if(str[i]<'0'||str[i]>'9')break;
for(k=i+1; k<=j; k++)
count1=count1*10+str[k]-'0';
if(str[i]=='-')count1=0-count1;
else ++i;//这里要特别注意,一定要有,即便uva的测试数据不准确,但要考虑到
root=new p;
root->pri=count1;
p *root1,*root2;
root1=v.top();
v.pop();
root2=v.top();
v.pop();
root->left=root1;
root->right=root2;
v.push(root);
}
}
flag=0;
sum(v.top(),0);
if(flag)printf("yes\n");
else printf("no\n");
}
return 0;
}
112 - Tree Summing
最新推荐文章于 2024-09-09 19:49:04 发布