Shortest Prefixes

本文提供了一个解决POJ 2001问题的代码示例,利用字典树(Trie)的数据结构进行字符串的插入与搜索操作。代码详细展示了字典树节点的定义、字符串插入、搜索及删除的方法。

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

http://poj.org/problem?id=2001

View Code
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct trie
{
    bool isstr ;
    int num ;
    trie *next[26] ;
} ;
void insert(trie *root, char *s)
{
    int i ;
    if(root==NULL||*s=='\0')
    return ;
    trie *p = root ;
    while(*s)
    {
        if(p->next[*s-'a']==NULL)
        {
            trie *q = (trie*)malloc(sizeof(trie)) ;
            for(i=0; i<26; i++)
            q->next[i] = NULL ;
            q->isstr = false ;
            q->num = 1 ;
            p->next[*s-'a'] = q ;
            p = p->next[*s-'a'] ;
        }
        else
        {
            p = p->next[*s-'a'] ;
            p->num++ ;
        }
        s++ ;
    }
    p->isstr = true ;
}
void search(trie *root, char *s)
{
    trie *p = root ;
    while(p&&*s)
    {
        if(p->next[*s-'a']->num==1)
        {
            printf("%c", *s) ;
            return ;
        }
        else
        printf("%c",*s) ;
        p = p->next[*s-'a'] ;
        s++ ;
    }
}
void del(trie *root)
{
    int i ;
    for(i=0; i<26; i++)
    {
        if(root->next[i]!=NULL)
        {
            del(root->next[i]) ;
        }
    }
    delete root ;
}
int main()
{
    //freopen("a.txt","r",stdin);
    int i ;
    char s[1010][25] ;
    trie *root = (trie*)malloc(sizeof(trie)) ;
    for(i=0; i<26; i++)
    root->next[i] = NULL ;
    root->isstr = false ;
    root->num = 1 ;
    int n = 0 ;
    while(gets(s[n]))
    {
        insert(root, s[n]) ;
        n++ ;
    }
    int t = 0 ;
    while(t<n)
    {
        printf("%s ",s[t]) ;
        search(root, s[t]) ;
        printf("\n") ;
        t++ ;
    }
    del(root) ;
    return 0 ;
}

 

转载于:https://www.cnblogs.com/yelan/archive/2013/04/01/2994171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值