圣诞节礼物(二叉查找树)
2012-05-31 15:30
225 查看
早上,脑袋有点卡,所以找了这道水题做做:http://www.bianchengla.com/oj/34/practise/problem?id=1731
刚读完题是感觉用hash比较好找,可是后来发现不是这么简单的,价格范围太大,开不了数组,而用二分查找的话,价格中又有重复,有人提示用二叉查找树,一想也对,于是顺便又复习了一下二叉树。
代码:
刚读完题是感觉用hash比较好找,可是后来发现不是这么简单的,价格范围太大,开不了数组,而用二分查找的话,价格中又有重复,有人提示用二叉查找树,一想也对,于是顺便又复习了一下二叉树。
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <algorithm> #include <math.h> #include <queue> #define maxx 100006 using namespace std ; struct node { int data ; int num ; struct node *left , *right ; }*root , *p ; struct node *creat() { struct node *t ; t = ( struct node *) malloc ( sizeof ( struct node )); t->left = t->right = NULL ; return t ; } void insert ( struct node *s , int x ) { if ( x == s->data ) { s->num++ ; return ; } if ( x < s->data ) { if ( s->left ==NULL ) s->left = p ; else insert ( s->left , x ); } else { if ( s->right == NULL ) s->right = p ; else insert ( s->right , x ); } } int find ( struct node *s , int x ) { if ( s->data == x && s->num > 0) { s->num--; return 1 ; } else if ( x < s->data ) { if ( s->left != NULL ) find( s->left , x ); else return 0; } else { if ( s->right != NULL ) find ( s->right , x ); else return 0 ; } } int main() { int n , m , i , j , x , y ; while ( scanf ( "%d%d" , &n , &m ) , n + m ) { root = creat( ); scanf ( "%d" , &x ); root->data = x ; root->num = 1 ; for ( i = 0 ; i < n - 1 ; i++ ) { scanf ( "%d" , &x ); p = creat( ) ; p->data = x ; p->num = 1 ; insert ( root , x ); } int flag = 0 ; for ( i = 0 ; i < m ; i++ ) { scanf ( "%d" , &x ); if ( !find ( root , x )) flag = 1 ; } if ( flag ) printf ( "NO\n" ); else printf ( "YES\n" ); } return 0; }
相关文章推荐
- Sun 在圣诞节前送出的最后礼物-NetBeans 5.5多国语言版释出!
- 关于圣诞节礼物的反思
- Sun 在圣诞节前送出的最后礼物-NetBeans 5.5多国语言版释出!
- 圣诞节诗歌-最美的礼物—赞美之泉
- jQuery动画-圣诞节礼物
- 圣诞节礼物
- 两年前和两年后的圣诞节的礼物
- 圣诞节平安夜主题(送给大家的小礼物)
- 谁在圣诞节送礼物?
- jQuery实现圣诞节礼物传送(花式轮播)
- 圣诞节送给妈妈的礼物
- 圣诞节的礼物!
- jQuery实现圣诞节礼物动画案例解析
- 圣诞节的正确打开方式,应该是这个样子丨钛空舱礼物清单
- jQuery实现花式轮播之圣诞节礼物传送效果
- 幸福的matrix67:MM送我的圣诞节礼物
- 圣诞节礼物之——圣诞节主题的免费屏幕保护程序
- 圣诞节礼物之——圣诞美好时光桌面主题
- 1731 圣诞节礼物
- Google送给中国博客的礼物,中文版Blogger.com