uva 839 Not so Mobile
2013-10-08 16:09
405 查看
这道题目给的数据的节点的遍历次序有点怪,有点像层次遍历,又有点像先序遍历,但都不是,所以要自己写一个比较怪的递归构建二叉树的函数,注意最开始的根节点没有出现在输入数据中,输入数据中的节点是从根节点的左儿子开始的,其实我比较讨厌一边读数据一边构建二叉树,但是这道题的数据数据比较麻烦,只能这样做了,否则没法判断一组数据是不是结束了,只有一边读一遍构建二叉树,递归构建的函数全部回溯完毕了,一组数据就刚好读完了,我觉得这也是这道题最烦人的一个地方,其他的没什么难度,就是二叉树的应用,二叉树构建出来之后,接下来的工作就简单了,利用先序遍历递归更新每个节点的重量数值,然后再先序遍历一次,检查每个节点是不是平衡的(叶子除外)。
#include <stdio.h> #include <set> #include <stdlib.h> using namespace std; char buffer[1000]; struct node { int weight; int distance; struct node *left, *right; }; struct node *root; void build_tree(struct node *root) { int wl, dl, wr, dr; scanf("%d %d %d %d", &wl, &dl, &wr, &dr); root->left = (struct node*)malloc(sizeof(struct node)); root->left->left = root->left->right = NULL; root->left->weight = wl; root->left->distance = dl; root->right = (struct node*)malloc(sizeof(struct node)); root->right->left = root->right->right = NULL; root->right->weight = wr; root->right->distance = dr; if(root->left->weight == 0) build_tree(root->left); if(root->right->weight == 0) build_tree(root->right); } void delete_tree(struct node *root) { if(root == NULL) return; delete_tree(root->left); delete_tree(root->right); free((void*)root); } //返回更新之后的节点的weight void update_weight(struct node *root) { if(root->left->weight == 0) update_weight(root->left); if(root->right->weight == 0) update_weight(root->right); root->weight = root->left->weight + root->right->weight; } //先序遍历 bool flag; void pre_travel(struct node * root) { if(!flag) return; if(root->left==NULL && root->right==NULL) return; if(root->left->distance*root->left->weight != root->right->distance*root->right->weight) { flag = false; return; } pre_travel(root->left); pre_travel(root->right); } void func() { update_weight(root); flag = true; pre_travel(root); } int main(void) { //freopen("input.dat", "r", stdin); int n, i; scanf("%d", &n); getchar(); for(i=1; i<=n; i++) { gets(buffer); root = (struct node*)malloc(sizeof(struct node)); root->weight = root->distance = 0; root->left = root->right = NULL; //重建二叉树 build_tree(root); func(); delete_tree(root); if(i >= 2) printf("\n"); if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }
相关文章推荐
- uva 839 Not so Mobile-S.B.S.
- UVa 839 - Not so Mobile
- UVA 839 - Not so Mobile
- uva 839 not so mobile——yhx
- uva 839 Not so Mobile 天平问题
- uva 839 Not so Mobile
- UVA 839 Not so Mobile
- ACM篇:UVa 839 -- Not so Mobile
- uva 839 Not so Mobile
- UVA 839 Not so Mobile(二叉树|DFS)
- uva 839 Not so Mobile(抽象意义上的建树)
- uva 839 Not so Mobile
- uva 839 - Not so Mobile
- UVA839 - Not so Mobile
- uva 839 (Not so mobile)天平 ---递归输入
- uva 839 Not so Mobile-S.B.S.
- UVA 839 Not So Mobile 【递归+树】
- UVa 839 Not so Mobile
- UVa 839 Not so Mobile (树的深度优先搜索)
- Not so Mobile UVA - 839