Before being an ubiquous communications gadget, a mobile was just a structure made of strings and wires suspending colourfull things. This kind of mobile is usually found hanging over cradles of small babies.
The figure illustrates a simple mobile. It is just a wire, suspended by a string, with an object on each side. It can also be seen as a kind of lever with the fulcrum on the point where the string ties the wire. From the lever principle we know that to balance a simple mobile the product of the weight of the objects by their distance to the fulcrum must be equal. That is Wl × Dl = Wr × Dr where Dl is the left distance, Dr is the right distance, Wl is the left weight and Wr is the right weight.
In a more complex mobile the object may be replaced by a sub-mobile, as shown in the next figure. In this case it is not so straightforward to check if the mobile is balanced so we need you to write a program that, given a description of a mobile as input, checks whether the mobile is in equilibrium or not.
输出一个树状天平,根据力矩相等原则判断是否平衡。
所谓力矩相等,就是Wl*Dl=Wr*Dr,,期中Wl和Wr分别为左右两边砝码的重量,D为距离。
采用递归(先序)方式输入:每个天平的格式为Wl,Dl,Wr,Dr,当Wl或Wr为0时,表示该(砝码)是一个子天平,接下来会描述这个子天平。当Wl=Wr=0时,会先描述左天平,然后是右天平。
题意就是这样,判断天平是否平衡。简单的递归,不过是以二叉树的形式。
#include<stdio.h>
int flag;
int w()
{
int w1,w2,d1,d2;
scanf("%d%d%d%d",&w1,&d1,&w2,&d2);
if(w1==0)
w1=w();//如果这一天平为0,则递归到下一层
if(w2==0)
w2=w();
if(w1*d1!=w2*d2)//如果这一层的天平不平,
{
flag=1;
}
return w1+w2;//返回上一层,计算这一层的总重量
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
flag=0;
w();
if(flag)
printf("NO\n");
else
printf("YES\n");
if(t)
printf("\n");
}
return 0;
}