HDU1305——Immediate Decodability

本文介绍了一种使用字典树(Trie)的数据结构来判断一个单词是否为另一个单词的前缀的方法。通过创建节点结构体和插入操作,可以高效地进行字符串匹配检查。该文提供了一个完整的C语言实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字典树模板套用,判断一个单词是否为某一单词的前缀

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int MAX=3;

typedef struct TrieNode
{
    int sign;  
    struct TrieNode *next[MAX]; 
} TrieNode;

TrieNode Memory[1000000]; 
int allocp = 0;
int fsign;

TrieNode * createTrieNode()
{
    TrieNode * tmp = &Memory[allocp++];
    tmp->sign = 0;
    for (int i = 0; i < MAX; i++)
        tmp->next[i] = NULL;
    return tmp;
}

void insertTrie(TrieNode * * pRoot, char * str)
{
    TrieNode * tmp = *pRoot;
    int i = 0, k;
   
    while (str[i])
    {
        k = str[i++] - '0'; 
        if (tmp->next[k])
        {
            if(tmp->next[k]->sign==1||str[i]=='\0')
            {
                fsign=0;
                return;

            }
        }
        else
        {
            tmp->next[k] = createTrieNode();
        }

        tmp = tmp->next[k];
        
    }
    tmp->sign=1;


}



int main()
{
    char s[15];
    int t,n;
    int i,j;
    TrieNode *p;
    t=1;
    fsign=1;
    allocp=0;
    p=createTrieNode();
    
    while(gets(s))
    {
            
            if(s[0]=='9')
            {
                if(fsign==1)
                {
                    printf("Set %d is immediately decodable\n",t++);


                }
                else
                {
                    printf("Set %d is not immediately decodable\n",t++);


                }
                allocp=0;
                fsign=1;
                p=createTrieNode();
            }
            else
            {

    
                if(fsign)
                {
                    
                    insertTrie(&p,s);
                }
                //printf("%s\n",s);
                
            }
            
        
    }


    
    

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值