POJ 2001 Shortest Prefixes(字典树基础)

题意:给出若干字符串,求每个字符串在所有字符串中唯一的最短前缀;

思路:将所有串插入字典树,对于每个串枚举前缀,查找唯一前缀;

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
    int num;
    node *next[26];
};
node *head;
char str[50005][55];
void init(node *h)
{
    for(int i=0;i<26;i++)
        h->next[i]=NULL;
    h->num=0;
}
void h_insert(char s[])
{
    node *t,*s1=head;
    int n=strlen(s);
    for(int i=0;i<n;i++)
    {
        int k=s[i]-'a';
        if(s1->next[k]==NULL)
        {
            t=new node;
            init(t);
            s1->next[k]=t;
        }
        s1=s1->next[k];
        s1->num++;
    }
}
int h_search(char s[])
{
    int cnt;
    node *s1=head;
    int n=strlen(s);
    for(int i=0;i<n;i++)
    {
        int k=s[i]-'a';
        if(s1->next[k]==NULL)
            return 0;
        s1=s1->next[k];
        cnt=s1->num;
    }
    return cnt;
}
void del(node *h)
{
    for(int i=0;i<26;i++)
    {
        if(h->next[i])
            del(h->next[i]);
    }
    delete(h);
}
char temp[50005];
int main()
{
    int i,j,k,len,shu=0;
    head=new node;
    init(head);
    while(scanf("%s",str[shu])!=EOF)
    {
        h_insert(str[shu]);
        shu++;
    }
    for(i=0;i<shu;i++)
    {
        printf("%s ",str[i]);
        memset(temp,0,sizeof(temp));
        len=strlen(str[i]);
        for(j=0;j<len;j++)
        {
            strncpy(temp,str[i],j);
            if(h_search(temp)==1)
            {
                printf("%s\n",temp);
                break;
            }
        }
        if(j==len) printf("%s\n",str[i]);
    }
    del(head);
    return 0;
}

 

posted on 2015-05-14 09:54  大树置林  阅读(131)  评论(0编辑  收藏  举报

导航