Not so Mobile |
Before being an ubiquous communications gadget, a mobile wasjust a structure made of strings and wires suspending colourfullthings. This kind of mobile is usually found hanging over cradlesof 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 beseen as a kind of lever with the fulcrum on the point where thestring ties the wire. From the lever principle we know that tobalance a simple mobile the product of the weight of the objectsby their distance to the fulcrum must be equal. That isWl×Dl = Wr×Drwhere Dl is the left distance, Dr is theright distance, Wl is the left weight and Wris the right weight.
In a more complex mobile the object may be replaced by asub-mobile, as shown in the next figure. In this case it is not sostraightforward to check if the mobile is balanced so we need youto write a program that, given a description of a mobile as input,checks whether the mobile is in equilibrium or not.
Input
The input begins with a single positive integer on a line by itself indicatingthe number of the cases following, each of them as described below.This line is followed by a blank line, and there is also a blank line betweentwo consecutive inputs.
The input is composed of several lines, each containing 4 integersseparated by a single space. The 4 integers represent thedistances of each object to the fulcrum and their weights, in theformat: Wl Dl Wr Dr
If Wl or Wr is zero then there is a sub-mobile hanging fromthat end and the following lines define the the sub-mobile. Inthis case we compute the weight of the sub-mobile as the sum ofweights of all its objects, disregarding the weight of the wiresand strings. If both Wl and Wr are zero then the followinglines define two sub-mobiles: first the left then the right one.
Output
For each test case, the output must follow the description below.The outputs of two consecutive cases will be separated by a blank line.
Write `YES' if the mobile is in equilibrium, write `NO' otherwise.
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;
思路:
递归不解释,数据出现0的时候就是递归的入口~
AC代码:
#include<stdio.h> int flag; int getW(int w) { int tw1, td1, tw2, td2; int p1, p2; if(w == 0) { scanf("%d %d %d %d", &tw1, &td1, &tw2, &td2); p1 = getW(tw1) * td1; p2 = getW(tw2) * td2; if(p1 == p2) return (p1/td1 + p2/td2); else { flag = 0; return -1; } } else return w; } int main() { int T; scanf("%d", &T); while(T--) { int w1, d1, w2, d2; int p1, p2; flag = 1; scanf("%d %d %d %d", &w1, &d1, &w2, &d2); p1 = getW(w1) * d1; p2 = getW(w2) * d2; if(p1 == p2 && flag == 1) { printf("YES "); if(T) printf(" "); } else { printf("NO "); if(T) printf(" "); } } return 0; }