poj 2001 Shortest Prefixes trie字典树

典型的字典树使用一个flag来标记是否是一个句子。现在我们可以用一个cout来标记这条路径是否有单词存在过,存在过几次

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

View Code
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

using namespace std;
struct node
{
    int count;//用来存有多少个单词存在过。
    int next[27];
}word[20100];
int num = 0;
char str[1000][25];
void new_node()
{
    num++;
    word[num].count = 0;
    for(int i = 0;i < 27;i++)
    word[num].next[i] = -1;
}
void insert(char *s,struct node word[])
{
    int i,dic;
    for(i = 0,dic = 0;s[i] != '\0';i++)
    {
        if(word[dic].next[s[i]-'a'] == -1)
        {
            new_node();
            word[dic].next[s[i]-'a'] = num;
        }
        dic = word[dic].next[s[i]-'a'];
        word[dic].count++;//存在就加1
    }
}
int search(char *s)
{
    int i,dic;
    for(i = 0,dic = 0;s[i] != '\0';i++)
    {
        if(word[dic].next[s[i]-'a'] != -1 )//说明这个地方没有,其实这道题不用加也可以因为都是出现过的单词。
        {
            dic = word[dic].next[s[i]-'a'];

            if(word[dic].count > 1)//出现过一次以上说明再往后就是这个单词自己走过的路径了
                printf("%c",s[i]);
            else
            break;
        }
        else
        break;
    }
    if(s[i] != '\0')//这个事控制与例子当中car的情形进行区分的。
    printf("%c",s[i]);
    puts("");
}
int main()
{
    int count = 0;
    num = -1;
    new_node();
    freopen("in.txt","r",stdin);
    while(scanf("%s",str[count]) != EOF)
    {
        insert(str[count],word);
        count++;
    }
    int i;
    for(i = 0;i < count;i++)
    {
        printf("%s ",str[i]);
        search(str[i]);
    }

    return 0;
}
posted @ 2012-07-26 17:45  某某。  阅读(150)  评论(0编辑  收藏  举报