圣诞节礼物(二叉查找树)

早上,脑袋有点卡,所以找了这道水题做做:http://www.bianchengla.com/oj/34/practise/problem?id=1731

刚读完题是感觉用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;
}
posted @ 2012-05-31 15:30  Misty_1  阅读(170)  评论(0编辑  收藏  举报