字典树---2001 POJ Shortest Prefixes(找最短前缀)

做的第一道字典树的题,算比较水的;

-->>>:传送门

代码:

 
#include <stdio.h>
#include<stdlib.h>
#define MAX 26
//using namespace std;
 
typedef struct TrieNode                     //Trie结点声明 
{
    //bool isStr;    
	int count;
	//标记该结点处是否构成单词 
    struct TrieNode *next[MAX];            //儿子分支 
}Trie;
 
void insert(Trie *root,const char *s)     //将单词s插入到字典树中 
{
    if(root==NULL||*s=='')
        return;
    int i;
    Trie *p=root;
    while(*s!='')
    {
        if(p->next[*s-'a']==NULL)        //如果不存在,则建立结点 
        {
            Trie *temp=(Trie *)malloc(sizeof(Trie));
            for(i=0;i<MAX;i++)
            {
                temp->next[i]=NULL;
            }
           // temp->isStr=false;
            p->next[*s-'a']=temp;
            p=p->next[*s-'a'];  
			p->count=1;
        }   
        else
        {
            p=p->next[*s-'a'];
			(p->count)++;
        }
        s++;
    }
   // p->isStr=true;                       //单词结束的地方标记此处可以构成一个单词 
}
 /*
int search(Trie *root,const char *s)  //查找某个单词是否已经存在 
{
    Trie *p=root;
    while(p!=NULL&&*s!='')
    {
        p=p->next[*s-'a'];
        s++;
    }
    return (p!=NULL&&p->isStr==true);      //在单词结束处的标记为true时,单词才存在 
}
 */
void findmin(Trie *root,char *str){
Trie *p=root;
while(*str!=''){
	if((p->next[*str-'a'])->count==1){
	printf("%c",*str);break;
	}
	printf("%c",*str);
	p=p->next[*str-'a'];
	str++;

}

}
void del(Trie *root)                      //释放整个字典树占的堆区空间 
{											//递归
    int i;
    for(i=0;i<MAX;i++)
    {
        if(root->next[i]!=NULL)
        {
            del(root->next[i]);
        }
    }
    free(root);
}
 
int main(int argc, char *argv[])
{
    int i,j;
  //  int n,m;                              //n为建立Trie树输入的单词数,m为要查找的单词数 
    char s[3000][25];
    Trie *root= (Trie *)malloc(sizeof(Trie));
    for(i=0;i<MAX;i++)
    {
        root->next[i]=NULL;
    }
    //root->isStr=false;
    //scanf("%d",&n);
    //getchar();
	int gsum=0;
    while(scanf("%s",s[gsum])!=EOF)
        //scanf("%s",s);
	{
		
		insert(root,s[gsum]);
		getchar();
		gsum++;
	}
   
   
        for(j=0;j<gsum;j++)                 //查找 
        {
printf("%s ", s[j]);
findmin(root,s[j]);
printf("
");

          //  scanf("%s",s);
           // if(search(root,s)==1)
           //     printf("YES
");
           // else
           //     printf("NO
");
        }
      //  printf("
");   
    
  //  del(root);                         //释放空间很重要 
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

today lazy . tomorrow die .
原文地址:https://www.cnblogs.com/france/p/4808770.html