題意:輸入一個樹狀天平,根據力矩相等的原則判斷是否平衡。就是W1D1= W2D2,其中W1,W2分別爲左右兩邊砝碼的重量,D爲距離。
示意圖如下:
個人代碼如下:
#include <iostream>
using namespace std;
#define IsLeaf(w1, w2) ((w1) && (w2))
bool solve(int &w)
{
int W1, L1, W2, L2;
cin>> W1 >> L1 >> W2 >> L2;
if(IsLeaf(W1, W2) == true)
{
//Leaf節點表示遞歸終止
w = W1 + W2;
return (W1 * L1 == W2 * L2);
}
else
{
bool b1 = true, b2 = true;
if(!W1) b1 = solve(W1); //Node節點進行遞歸
if(!W2) b2 = solve(W2); //Node節點進行遞歸
w = W1 + W2;
return b1 && b2 && (W1 * L1 == W2 * L2);
}
}
int main()
{
int w = 0;
if(solve(w)) cout<< "YES";
else cout<< "NO";
return 0;
}
結果: