UVA 112 Tree Summing

本文探讨了一种非标准表示的树结构,其中包含节点权重和父子关系。重点在于识别是否存在一条从根节点到叶节点的路径,其累计权重等于预设值。通过解析输入字符串并构建树模型,实现路径查找算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:   用一种奇怪的方法表示一棵树   ( 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值