您的位置:首页 > 其它

紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)

2017-04-15 15:23 274 查看
题意:输入一个树状天平,看是否都符合力矩相等。递归输入每个节点(天平)。第一种是用指针来建树,然后逐步向上更新判断

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;

struct node
{
int v,w1,d1,w2,d2;
node *l,*r;
node(int a=0,node *left=NULL,node *right=NULL)
{
v=a,l=left,r=right;
}
};
node *root;
int flag=0;
node* buildtree(node *t)
{
int w1,d1,w2,d2;
scanf("%d %d %d %d",&w1,&d1,&w2,&d2);
t->d1=d1,t->d2=d2,t->w1=w1,t->w2=w2;
if(!w1) {
if(t->l==NULL){t->l=new node();}
buildtree(t->l);
}
if(!w2){
if(t->r==NULL) {t->r=new node();}
buildtree(t->r);
}
if(t->l!=NULL)//更新上面节点的W
t->w1+=(t->l)->w1+(t->l)->w2;
if(t->r!=NULL)
t->w2+=(t->r)->w1+(t->r)->w2;
if(t->w1*t->d1!=t->w2*t->d2) flag=1;
}
int main()
{
int T,case1=0;
scanf("%d",&T);
while(T--)
{
if(case1) printf("\n");
flag=0;
root =new node();
buildtree(root);
if(flag==1) printf("NO\n");
else printf("YES\n");
case1=1;
}
return 0;
}


第二种是用引用的方法,代码更精简

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <cmath>

using namespace std;
int flag=0;
void solve(int &w)
{
int w1,d1,w2,d2;
cin>>w1>>d1>>w2>>d2;
if(!w1) solve(w1);
if(!w2) solve(w2);
w=w1+w2;
if(w1*d1!=w2*d2) flag=1;
}
int main()
{
int T,w;
scanf("%d",&T);
while(T--)
{
flag=0;
solve(w);
if(!flag) printf("YES\n");else printf("NO\n");
if(T) printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: