zoukankan      html  css  js  c++  java
  • 圣诞节礼物(二叉查找树)

    早上,脑袋有点卡,所以找了这道水题做做: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;
    }
  • 相关阅读:
    话说打工
    Linux系统信息查看命令大全
    基于LNMP的Zabbbix之Zabbix Server源码详细安装,但不给图
    基于LNMP的Zabbbix之PHP源码安装
    php --with-mysql=mysqlnd
    LeetCode:Binary Tree Level Order Traversal
    tslib-触摸屏校准
    A
    【雷电】源代码分析(二)-- 进入游戏攻击
    能够替代浮动的inline-block
  • 原文地址:https://www.cnblogs.com/misty1/p/2528533.html
Copyright © 2011-2022 走看看