题目中的意思是要程序去判断天平是否平衡,不一样的地方是,这里的天平托盘上有可能还存在子天平(输入的w为0时),也就是说要保证每一个天平都平衡,并且采用的是使用递归的方式,左面的优先判断。
要使天平平衡,就要使天平上的每一个子天平都达到平衡状态,当不平衡的时候,所有的都不平衡。
首先传入参数0,表示一开始没有天平,然后逐渐读入4个数字创建天平。
当子天平存在时,优先判断左天平再去判断右天平。当子天平不再创建的时候,就将当前天平上的质量相加起来,再根据力矩去判断左右是否平衡(默认最小的天平是平衡的,防止出错)。
返回值是当前天平和所有子天平的平衡状态。
下面是代码:
#include <bits/stdc++.h>
using namespace std;
bool judge(int & weight)
{
int weight1, dis1, weight2, dis2;
cin >> weight1 >> dis1 >> weight2 >> dis2;
bool tree1 = true, tree2 = true;//表示一个子天平默认平衡,防止最小的天平判断出错
if (!weight1)//left
tree1 = judge(weight1);
if (!weight2)//right
tree2 = judge(weight2);
weight = weight1 + weight2;//now judge
//cout << weight << endl;
return tree1 && tree2 && (weight1*dis1 == weight2 * dis2);
}
int main()
{
//freopen("t.txt", "w", stdout);
int CASE, temp = 0;
cin >> CASE;
while (CASE--)
{
if (judge(temp))
cout << "YES" << endl;
else
cout << "NO" << endl;
if (CASE)
cout << endl;
}
//system("pause");
return 0;
}