UVa839天平树

题意:输入一个树状天平,根据力矩相等原则(力臂乘质量)判断是否平衡。按照递归(先序)方式输入,若输入的W(质量)为0说明该“砝码”是个子天平,接下来会描述该子天平。

思路:采用递归输入我们自然想到递归处理,在输入过程判断,采用引用传值,将子天平的砝码传给该子天平。

代码:

#include<bits/stdc++.h>
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);//当两个子天平都平衡并且自身也平衡返回true。
}

int main()  {
    int T,W;
    cin>>T;
    while(T--)  {
        if(solve(W))    cout<<"YES
";else cout<<"NO
";
        if(T)    cout<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/depth/p/5749730.html