UVa839:佛系建树与数据更新

题目链接传送门

思路:

1. 首先题目的输入是先序递归的,那么首个问题就是是否要建树,如何建树,怎么存树。更具体一点,如何知道这棵树建好了。输入只告诉我们总共有几棵树(几个天平),每棵树的构造指令作为一块用一个空行与其他指令隔开。所以首先就想到用string搭配stringstream来输入。但是细想输入数据是怎么确定这棵树建造好了呢?我们考查其建树规则:发现一旦有一个0,就要在相应的方向(左手or右手)建树;一旦这不是0,就相当于建树建到了叶子了。这种递归建树规则不就完全可以用来写递归函数然后递归函数帮我们自动识别树是否建好(数据合法)!?所以,遇见递归输入的问题我们可以根据递归规则(何时进入下一层何时返回)来建树或者直接判断。

2. 接着,对于树的权值除了用树的遍历方法外,还可以通过传引用的方法实现数据的记录更新

#include<bits/stdc++.h>
using namespace std;
//to judge whether the current scale is balanced and update the weight with the summary weight of the two sides of the scale
bool is_balanced(int &weight){
	int w1, d1, w2, d2;
	scanf("%d%d%d%d", &w1, &d1, &w2, &d2);
	bool left_balanced, right_balanced;
	if(!w1) left_balanced = is_balanced(w1);
	else left_balanced = true;
	if(!w2) right_balanced = is_balanced(w2);
	else right_balanced = true;
	weight = w1 + w2;
	return left_balanced && right_balanced && w1 * d1 == w2 * d2;
}

int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	
	int kase;
	scanf("%d", &kase);
	int weight;
	while(kase--){
		if(is_balanced(weight)) printf("YES\n");
		else printf("NO\n");
		if(kase) putchar('\n');
	}
	
	//printf("Total time: %.3f s.\n", (double)clock()/CLOCKS_PER_SEC);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值