hdu 4825字典树

这道题是字典树+贪心的思想,一棵树 两个孩子 0 或者 1;

并且参考了这位大神的    点击打开http://blog.csdn.net/u013761036/article/details/33740467

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


typedef struct Tree
{
    Tree *next[2];
}Tree;


void Buid_Tree(char *str,Tree *T)
{
    int len = 34;
    Tree *q,*p=T;
    for(int i = 0 ;i < len ;i ++)
    {
       int id = str[i] - '0';
       if(p -> next[id] == NULL)
       {
           q = (Tree *) malloc(sizeof(Tree));
           for(int j = 0 ;j < 2 ;j ++)
           q -> next[j] = NULL;
           p ->next[id] = q;
           p = p -> next[id];
       }
       else p = p -> next[id];
     }
}


__int64 Find(char *str,Tree *T)
{
    int len = 34;
    Tree *p = T;
    __int64 K = 2;
    K <<= 32;
    __int64 sum = 0;
    for(int i = 0 ;i < len ;i ++)
    {
        int id = str[i] - '0';
        if(p -> next[id] == NULL)
        p = p -> next[id ^ 1];
        else
        {
            p = p -> next[id];
            sum += K;
        }
        K = K / 2;
    }
    return sum;
}


void get_str(char *str ,__int64 num)
{
    int t = 34;
    str[t] = '\0';
    while(num)
    {
       str[--t] = (num & 1) + '0';
       num >>= 1;
    }
    for(int i = t - 1 ;i >= 0 ;i --)
    str[i] = '0';
}


int main ()
{
    int i ,t ,n ,m ,cas = 1;
    __int64 num;
    Tree *T=(Tree *)malloc(sizeof(Tree));
    char str[50];
    scanf("%d" ,&t);
    while(t--)
    {
        scanf("%d %d" ,&n ,&m);
        T->next[0]=T->next[1]=NULL;
        while(n--)
        {
            scanf("%I64d" ,&num);
            get_str(str ,num);
            Buid_Tree(str,T);
        }
        printf("Case #%d:\n" ,cas ++);
        while(m--)
        {
           scanf("%I64d" ,&num);
           get_str(str ,num);
           for(i = 0 ;i < 34 ;i ++)
           if(str[i] == '1') str[i] = '0';
           else str[i] = '1';
           printf("%I64d\n" ,Find(str,T) ^ num);
        }
    }
    return 0;
}



备忘~~~~~~~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值