UVA839 天平 Not so Mobile

知识点:二叉树遍历

这个题刘汝佳的代码写的很巧妙,但是我看了一眼看不懂就先不看了,用的笨方法做的,刘汝佳的方法过段时间再看

这个题可以抽象成一个二叉树的模型,每个节点储存的数据有四个,就是输入的四个数据,然后我们设计一个递归函数,返回这个子树的重量,返回之前比较一下这个子树两边是不是平衡的,只要有一个不平衡那就是NO,

#include <bits/stdc++.h>

using namespace std;

struct node {
	int wl, dl, wr, dr;
	int lchild, rchild;
	node() {}
	node(int a, int b, int c, int d, int e, int f) {
		wl = a; dl = b; wr = c; dr = d; lchild = e; rchild = f;
	}
} tree[10005];

int tot;
bool flag;

int create() {
	int wl, dl, wr, dr;
	cin >> wl >> dl >> wr >> dr;
	int root = ++tot;
	tree[root] = node(wl, dl, wr, dr, -1, -1);
	if (!wl) tree[root].lchild = create();
	if (!wr) tree[root].rchild = create();
	return root;
}

int solve(int root) {
	int w1 = tree[root].wl;
	if (tree[root].lchild != -1) w1 += solve(tree[root].lchild);
	int w2 = tree[root].wr;
	if (tree[root].rchild != -1) w2 += solve(tree[root].rchild);
	if (w1 * tree[root].dl != w2 * tree[root].dr) flag = false;
	return w1 + w2;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		tot = 0;
		flag = true;
		int root = create();
		int tmp = solve(root);
		cout << (flag ? "YES" : "NO") << endl;
		if (T) cout << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值