字典树

来源:互联网 发布:2017总决赛数据 编辑:程序博客网 时间:2024/05/16 19:14
#include<cstdio>#include <cstdlib>#include <stdio.h>#include<sstream>#include<malloc.h>#include<string>#include<cstring>#include<iostream>using namespace std;struct Node{    struct Node *child[26];char res[32];bool flag;}root;void init(struct Node *node){//node=(struct Node*)malloc(sizeof(struct Node));for(int i=0;i<26;i++){node->child[i]=NULL;node->flag=0;}}int insert(char *word,char *chg){int len=strlen(word);if(len==0)return 0;struct Node *Now=&root;for(int i=0;i<len;i++){if(Now->child[word[i]-'a']==NULL){struct Node *NewNode=(struct Node*)malloc(sizeof(struct Node));//NewNode不能定义为变量//要定义为指针,重新分配空间。否则Now指针一直指向同一个空间init(NewNode);//NewNode->n=1;Now->child[word[i]-'a']=NewNode;Now=NewNode;}else{Now=Now->child[word[i]-'a'];//Now->n++;}}Now->flag=1;int j=0;while(chg[j]!='\0'){Now->res[j]=chg[j];j++;}Now->res[j]='\0';return 0;}string find(char *s){int len=strlen(s);int cnt=0;struct Node *tmp=&root;for(int i=0;i<len;i++){if(tmp->child[s[i]-'a']==NULL){//cout<<s;return "0";}else{tmp=tmp->child[s[i]-'a'];}}if(tmp->flag==0)return "0";//cout<<s;else{/*a=0;int i=0;while(father[i]!='\0' || tmp->res[i]!='\0' ){if(father[i]!=tmp->res[i]){   a= 1;break;}i++;}if(a==1)find(tmp->res,father);elsecout<<s;*/return tmp->res;}}void del(struct Node *t) //删除Trie树,并释放空间{for(int i=0;i<26 ;i++){if(t->child[i] != NULL){del(t->child[i]) ;}}free(t);}int main(){int k=1;int n,m;char word[32];char chg[32];char str[110];char tmp[32];char tmp2[32];string ss,sss;string tt;int t,i,j;cin>>t;while(t--){        init(&root);scanf("%d%d",&n,&m);for(i=0;i<m;i++){scanf("%s",&word);scanf("%s",&chg);insert(word,chg);}getchar();gets(str);istringstream is(str);printf("Case #%d: ",k++);while(is>>tmp){for(i=0;i<n-1;i++){sss=find(tmp);if(sss=="0"){cout<<tmp;break;}for(j=0;j<sss.length();j++)tmp[j]=sss[j];tmp[j]='\0';}if( sss!="0" )cout<<sss;printf(" ");}printf("\n");//del(&root);}return 0;}