POJ 2001 Shortest Prefixes(字典树)

来源:互联网 发布:梦幻西游mac版字体小 编辑:程序博客网 时间:2024/03/29 20:17

题目链接:Shortest Prefixes


题意:n个字符串,求每个字符串的最短非公共前缀,若没有输出其本身


思路:利用字典树记录每个前缀使用的次数,以前标记作用的flag当做计数功能,所以使用次数非1的肯定是与其他字符串存在前缀,从首字母到第一非1的字符就是最短非公共前缀;



#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>const int N = 20010;using namespace std;struct node{    int flag;    node *next[26];};int n,m;struct node *make(){    node *root = new node;    for(int i = 0;i<26;i++)        root->next[i] = NULL;    root->flag = 1;    return root;}struct node *creat(){    node *p = new node;    for(int i = 0;i<26;i++)        p->next[i] = NULL;    p->flag = 0;    return p;}void Insert(struct node *p,char *a){    int len = strlen(a);    int num;    node *q;    for(int i = 0;i<len;i++)    {         num = a[i]-'a';        if(p->next[num]==NULL)        {            //q=(struct node *)calloc(1,sizeof(struct node));            q = creat();            p->next[num] = q;            p = q;            p->flag = 1;        }        else        {            p = p->next[num];            p->flag++;        }      // printf("%d %c |", p->flag, a[i]);    }   // p->flag++;}void Search(struct node *p,char *a){    int len = strlen(a);    for(int i = 0;i<len;i++)    {//        int num = a[i]-'a';//        char c = 'a' + num;//        putchar(c);//        if(p->flag==1)//            break;//            else//                p= p->next[num];            int num=a[i]-'a';         p=p->next[num];         printf("%c", a[i]);         if(p->flag==1)            break;    }}/*void Search(struct node *p,char *a){    int len = strlen(a);    for(int i = 0;i<len;i++)    {        int num = a[i]-'a';        char c = 'a' + num;        putchar(c);        if(p->flag==1)            break; p= p->next[num];    }}*/void FREE(struct node *root){    if(root==NULL)return;    for(int i = 0;i<26;i++)    {        if(root->next[i]!=NULL)        FREE(root->next[i]);    }    free(root);    root = NULL;}int main(){    char a[1010][30];    node *root;    root = make();    n=0;    while(~scanf("%s",a[n]))    {        //node *root = new node;        Insert(root,a[n]);       // printf("\n");        n++;    }    for(int i = 0;i<n;i++)    {        printf("%s ",a[i]);        Search(root,a[i]);        cout<<endl;    }    FREE(root);   //system("pause");    return 0;}


0 0
原创粉丝点击