题意:给出一个sum值,判断一棵树沿着根节点到叶子节点路径上所有节点权值之和与sum是否相等
回溯法!自己写的算法疯狂TLE,看了大佬的博客,誓与大佬同归于尽
#include<bits/stdc++.h>
#define LL long long
#define maxn 100010
using namespace std;
int sum;
bool flag=false;
bool tree_sum(int n)
{
int num;
char ch;
cin>>ch;
if(cin>>num)
{
n+=num;
bool temp=tree_sum(n)|tree_sum(n);
if(!temp&&sum==n)
{
flag=true;
}
cin>>ch;
return true;
}
else
{
cin.clear();
cin>>ch;
return false;
}
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
while(cin>>sum)
{
flag=false;
tree_sum(0);
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
本文介绍了一种解决树形结构中从根节点到叶子节点路径权值总和与给定值比较的问题。通过递归回溯的方法实现,判断路径权值之和是否等于预设值,最终输出yes或no。
1386

被折叠的 条评论
为什么被折叠?



