题意:输入一个树状的天平,根据力矩原理判断是否平衡
这题是典型的深度优先搜索问题,先用递归的方式录入数据、建立树,然后再利用后序遍历,从叶节点的父节点开始,一边计算当前节点的重量,一边计算左右子节点是否满足w1*l1==w2*l2
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int w1,w2,l1,l2;
int WL1,WL2;
bool ans=true;
struct Node
{
int W;
int L;
Node* left;
Node* right;
Node():W(0),L(0),left(NULL),right(NULL){}
};
Node* newnode(){return new Node();}
Node* root=newnode();
void input(Node* u)
{
scanf("%d%d%d%d",&w1,&l1,&w2,&l2);
if(u->left==NULL) u->left=newnode();
if(u->right==NULL) u->right=newnode();
u->left->W=w1; u->left->L=l1;
u->right->W=w2; u->right->L=l2;
if( w1==0 && w2==0)
{
input(u->left);
input(u->right);
}
}
void dfs(Node* u)
{
if(u!=NULL && ans)
{
// printf("left\n");
dfs(u->left);
// printf("right\n");
dfs(u->right);
if(u->left!=NULL)
{
u->W=(u->left->W)+(u->right->W);
WL1=(u->left->W)*(u->left->L);
// printf("W1\n");
WL2=(u->right->W)*(u->right->L);
// printf("W2\n");
if(WL1!=WL2) ans=false;
}
}
}
//void trans(Node* u)
//{
// if(u!=NULL)
// {
// trans(u->left);
// trans(u->right);
// printf("%d ",u->W);
// }
//}
int main()
{
Node* u=root;
input(u);
dfs(u);
// trans(u);
printf("\n %d",ans?1:0);
return 0;
}