【Uva839】Not so Mobile

题目链接

题意:

输入一个树状天平,根据力矩相等yuan原则判断是否平衡。所谓力矩相等,就是WlDl=WrDr,其中Wl和Wr分别为左右两边砝码的重量,D为距离。

采用递归(先序)方式shu输入,每个天平的格式为Wl,Dl,Wr,Dr,当Wl或Wr为0时,表示ga该“砝码”实际是一个子天平,接下来会描述这个子天平。当Wl=Wr=0时,会先描述左子天平,然后是右子天平。

解题思路:

其实就是模拟建立二叉树的过程,数据是根据先序输入的,W是否为0就是判断是否有子树,每输入一个子天平就要返回子天平是否平衡,w=W1+W2即返回的是修改后子天平的总重量。

代码:

#include<cstdio>
#include<iostream>
using namespace std;
bool solve(int &w)
{
	int W1,D1,W2,D2;
	bool b1=true,b2=true;
	cin>>W1>>D1>>W2>>D2;
	if(!W1)b1=solve(W1); //递归左子树 
	if(!W2)b2=solve(W2); //递归右子树 
	w=W1+W2;
	return (b1 && b2 && W1*D1==W2*D2);
}
int main()
{
	int repeat,w;
	cin>>repeat;
	while(repeat--){
		if(solve(w))cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
		if(repeat)cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/81070756
so
SO?
今日推荐