输入一个树状天平,根据力矩相等原则判断是否平衡。如图所示,所谓力矩相等,就是Wl Dl=Wr Dr,其中Wl和Wr分别为左右两边砝码的重量,D为距离。
采用递归(先序)方式输入:每个天平的格式为Wl ,Dl,Wr,Dr,当Wl 或 Wr为0时,表示该砝码实际上是一个子天平,接下来会描述这个子天平。当Wl = Wr =0时,会先描述左子天平,然后是右子天平。
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
解题思路:
思路链接:
https://blog.csdn.net/qq_40744839/article/details/106006249?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161596262716780265438676%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=161596262716780265438676&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v29-10-106006249.pc_search_result_hbase_insert&utm_term=uva839
代码如下:
#include <iostream>
using namespace std;bool solve(int &w) {int w1, d1, w2, d2;bool b1 = true, b2 = true;cin >> w1 >> d1 >> w2 >> d2;if (!w1)b1 = solve(w1);if (!w2)b2 = solve(w2);w = w1 + w2;return b1 && b2 && (w1 * d1 == w2 * d2);
}int main() {int cnt, w;cin >> cnt;while (cnt--) {if (solve(w))cout << "YES" << endl;elsecout << "NO" << endl;if (cnt)cout << endl;}return 0;
}