紫书章六例题九 天平 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; }
相关文章推荐
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 紫书章六例题九 天平 UVA 839(更新二叉树的节点上的值)
- 例题6-9 天平 UVa 839 递归
- 6_9 天平(UVa839)<二叉树的DFS>
- 入门经典-6.3.3二叉树递归遍历-uva839天平-先序遍历,引用传值
- 例题6-9UVA839 - Not so Mobile 递归访问二叉树
- UVa839_(二叉树递归_天平问题)
- uva-839天平
- UVA 839 Not so Mobile(二叉树经典题)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- UVa 839-Not so Mobile(天平)
- UVA 839 Not so Mobile(二叉树|DFS)
- uva 839 紫书例题及代码理解
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)