Not so Mobile (天平)

       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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值