天平 (p157, 二叉树的 DFS)

天平 (p157, 二叉树的 DFS)

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.
 

QQ图片20181220180714.png


 
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.
 

QQ图片20181220180823.png

Sample Input
1
0 2 0 4

0 3 0 1

1 1 1 1

2 4 4 2

1 6 3 2
Sample Output
YES

由于杠杆原理可知,当w1*d1=w2*d2时,天平会平衡,而每一个天平的w为0代表有小天平存在,这时的w其实为小天平的w1+w2,输入的时候可以写成递归形式的输入格式来保证数据能够输入完毕

代码如下

#include<stdio.h>
int flag;
int dfs()
{
	int w1, d1, w2, d2;
	
	scanf("%d %d %d %d", &w1, &d1, &w2, &d2);//输入每一个天平的两端长度和重量 
	
	if(!w1)                     //当天平重量为0时,代表有小天平,小天平的输入从左到右赋值 
	
		w1 = dfs();
	
	if(!w2)
	
		w2 = dfs();
	
	if( w1 * d1 == w2 * d2)
		
		return w1+w2;                   //向上回溯小天平的重量 
	
	else                                //当天平两端不等时,标记一下
                                            //存在小天平两端都不相等的情况,
                            //不标记的话结果两端都回溯0,结果就错了                         
	{
		
		flag = 1;
		
		return 0;
	}
	
}
int main()
{
	
	int t;
	
	scanf("%d", &t);
	while(t--)
	{
		
		if(dfs()&&!flag)
		
			printf("YES\n");
		
		else
			printf("NO\n");
		
		flag = 0;
		
		if(t)
			
			printf("\n");
	}
}

猜你喜欢

转载自blog.csdn.net/w__000000wbt/article/details/85137920
今日推荐