Poj 2001 Shortest Prefix(字典树模板)

字典树入门题......

只需在对应结点记录num值,找到num为1时的前缀,是唯一前缀(只是该单词的前缀),或者一直找找到该单词结尾。


#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 1050
#define INF 0x7FFFFFFF
# define eps 1e-5
//#pragma comment(linker, "/STACK:36777216") ///传说中的外挂
using namespace std;

char s[1005][25];
char ss[25];
struct node
{
    node *next[30];
    int num;
    node ()
    {
        num=0;
        for(int i=0; i<26; i++)
            next[i] = NULL;
    }
} * root;

void insert(char *s)
{
    node *p = root;
    int i,len;
    len = strlen(s);
    for(i=0; i<len; i++)
    {
        int v = s[i] - 'a';
        if(p->next[v] == NULL)
        {
            p->next[v] = new node;
        }
        p->next[v]->num ++;
        p = p->next[v];
    }
}

void *search(char *s)
{
    node *p = root;
    int q=0,i;
    int len = strlen(s);
    for(i=0; i<len; i++)
    {
        ss[q++] = s[i];
        int v = s[i] - 'a';
        if(p->next[v]->num == 1) // 该字母在当前层数只出现过一次
        {
            ss[q] = '\0';
            return ss;
        }
        p = p->next[v];
    }
    ss[q] = '\0';
    return ss;
}

int main()
{
    int i=0;
    root = new node;
    while(cin >> s[i])
        insert(s[i++]);
    for(int j=0; j<i; j++)
    {
        printf("%s %s\n",s[j],search(s[j]));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值