单词的前缀

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)

Total Submission(s) : 167   Accepted Submission(s) : 46

Font: Times New Roman | Verdana | Georgia 

Font Size: ← →

Problem Description

ZZY 针对某个单词表给单词定义了特别的前缀,该前缀使得在该表中可以唯一标识某个单词,并且前缀的长度是最短。若有单词是另一个单词的前缀,那么该单词的前缀就是其本身。 

Input

输入包含多组数据,对于每组数据,第一行是整数N(1~1000) ,表示单词表中单词的个数,接下来是N行,分别表示一个单词,每个单词长度不超过20 位,并且都是小写字母组成。

Output

对每组输入,输出2行,第一行输出“***Case 组号,接下按之前的单词表顺序,输出N行,每行由单词表中的单词和前缀组成,中间用空格隔开

Sample Input

a

10

lap

njzatz

jhjn

ousua

j

lhdahl

gtmz

xxisug

tv

aho

Sample Output

***Case 1

a a

***Case 2

lap la

njzatz n

jhjn jh

ousua o

j j

lhdahl lh

gtmz g

xxisug x

tv t

aho a

代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
char s[1005][25];

struct node
{
  node *next[26];
  int n;    
};

node *root;

void insert(char *s)
{
   node *p,*q;
   int len;
   len=strlen(s);
   if(len==0)
   return ;
   p=root;
   for(int i=0;i<len;i++)
   {
      if(p->next[s[i]-'a']==0) 
   {
    q=(node *)malloc(sizeof(node)); 
    for(int j=0;j<26;j++)
    q->next[j]=0;
    p->next[s[i]-'a']=q;
    p=q;
    p->n=1;         
      }  
   else
   {   
         p=p->next[s[i]-'a'];
      p->n=p->n+1;  
      }
   }  
}

void find(char *s)
{
    int len;
    node *p;
    p=root;
 len=strlen(s);
 if(len==0)
 return ;
 printf("%s ",s);
  

 for(int i=0;i<len;i++)
 {
       p=p->next[s[i]-'a'];    
           if(p->n==1)
           {
           printf("%c",s[i]);
           return ;
     }
           else
           printf("%c",s[i]);
    }
  
}

int main()
{
   int num=1;
   int t;
   while(scanf("%d",&n)!=EOF)
   {
        
      root=(node *)malloc(sizeof(node));
      for(int i=0;i<26;i++)
      root->next[i]=0;
   root->n=0;    
   for(int i=0;i<n;i++)
   {
     scanf("%s",s[i]);
  insert(s[i]);    
      } 
      printf("***Case %d\n",num++);
   for(int i=0;i<n;i++)
   { find(s[i]); 
     printf("\n");
      }      
   }  
   system("pause");
   return 0;
}