题意:给出一个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;
}