112 - Tree Summing***

2835 단어
/*
 
 、 , 
 : 
 : 
 : 
cin.clear() 
*/
/* :
#include <iostream>
#include <string>
using namespace std;
bool ok;
bool tree_sum(int n,int sum)
{
	char ch;
	cin>>ch;
	int v;
	if(!((cin>>v)==0))
	{
		n+=v;
		bool t;
		t=tree_sum(n,sum)|tree_sum(n,sum);
		if(!ok && !t)
			ok=(n==sum);
		cin>>ch;
		return true;
	}
	else
	{
		cin.clear();
		cin>>ch;
		return false;
	}
}
int main()
{
	int sum;
	while(!((cin>>sum)==0))
	{
		ok=false;
		tree_sum(0,sum);
		cout<<(ok?"yes":"no")<<endl;
	}
	return 0;
}
*/
////////////////////////////////// :
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
bool ok;
struct Node
{
	Node *lchild,*rchild;
};
Node *creat_tree(int n,int sum)
{
	char ch;
	cin>>ch;
	int v;
	if(!((cin>>v)==0))
	{
		n+=v;
		Node *root=(Node *)malloc(sizeof(Node));
		root->lchild=creat_tree(n,sum);
		root->rchild=creat_tree(n,sum);
		
		if(!ok && root->lchild==NULL && root->rchild==NULL)
			ok=(n==sum);
		cin>>ch;
		return root;
	}
	else
	{
		cin.clear();
		cin>>ch;
		return NULL;
	}
}
int main()
{
	int sum;
	while(!((cin>>sum)==0))
	{
		ok=false;
		creat_tree(0,sum);
		cout<<(ok?"yes":"no")<<endl;
	}
	return 0;
}

두 번째 작업, C로 구현, 결과 Runtime error
#include <cstdio>
#include <cstring>
const int nMax=100000000;//Runtime error: , Runtime error, ?
int I;
char T[nMax];
int m;
int tree[nMax];
bool ok;
void init()
{
	int flag=0;
	int first=1;
	while(first || flag)
	{
		char c=getchar();
		if(c==' ' || c=='\t' || c=='
') continue; else if(c=='(') {flag++;if(first) first=0;} else if(c==')') {flag--;if(first) first=0;} T[m++]=c; } } int get_dig(int i,int &k) { int num=0; int p=1; if(T[i]=='-') { p=-1; i++; } else if(T[i]=='+') i++; while(T[i]>='0' && T[i]<='9') { num=num*10+T[i]-'0'; i++; } k=i; return p*num; } int build(int k,int cur) { int a,p; int x,y; a=get_dig(k+1,p); if(p==k+1) { tree[cur]=-1; return k+2; } else { tree[cur]=a; x=build(p,2*cur); y=build(x,2*cur+1); return y+1; } } void traverse(int cur,int num) { if(!ok) { if(tree[cur]==-1) { if(num==I) ok=1; return; } traverse(2*cur,num+tree[cur]); traverse(2*cur+1,num+tree[cur]); } } int main() { //freopen("f://data.in","r",stdin); while(scanf("%d",&I)!=EOF) { m=0; ok=0; init(); build(0,1); traverse(1,0); if(ok) printf("yes
"); else printf("no
"); } return 0; } /* , C scanf , cin , : scanf, cin, */

좋은 웹페이지 즐겨찾기