https://odzkskevi.qnssl.com/a2ea37834edbbaa8afe720b6f12e7707?v=1533523822
题意:输入一个树状天平,根据力矩相等原则(力臂乘质量)判断是否平衡。按照递归(先序)方式输入,若输入的W(质量)为0说明该“砝码”是个子天平,接下来会描述该子天平。
思路:采用递归输入我们自然想到递归处理,在输入过程判断,采用引用传值,将子天平的砝码传给该子天平。
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
int judge()
{
int wl,dl,wr,dr;int w;//wl为左砝码的重量,wr是右砝码的重量,dl是左砝码的距离,dr是由砝码的距离
cin>>wl>>dl>>wr>>dr;
if(wl==0) wl=judge();//若该“砝码”是子天平,则进行递归,得到该节点的重量
if(wr==0) wr=judge();//上同
if(wl*dl==wr*dr&&dl&&dr) w=wl+wr;//两砝码的距离必须存在,即大于0,否则会出错。平衡则返回总质量
else w=0;//不平衡则质量为0
return w;
}
int main()
{
int n,w;
cin>>n;
while(n--)
{
w=judge();
if(w) printf("YES\n"); else printf("NO\n");
if(n) cout<<endl;
}
return 0;
}