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

来源:互联网 发布:媒体矩阵 是什么意思 编辑:程序博客网 时间:2024/06/07 08:06

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

#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;}
0 0