暑假- Trie树-(B - Babelfish)

来源:互联网 发布:用友软件出纳签字 编辑:程序博客网 时间:2024/05/11 15:36
/*题意:输入一个字典[解释,方言],给你一些串,求你翻译后的串,若不存在则输出"eh"思路:trie树,结点保存的信息为一个字符串[即解释]。*/#include<iostream>  #include<cstring> #include<stdio.h>using namespace std;  const int MAXN=200000;struct Node  {      char value[15];//结点的值(本题值是一个字符串)    int child[26]; //结点的下一层[它的孩子]    Node() //构造函数,初始化    {          value[15]='\0';        memset(child,0,sizeof(child));      }  };  Node trie[MAXN];int trieN=0; char temp[15];//保存返回的信息。void Insert(char a[],char s[]) //插入函数[构造trie树]{      int x=0;      for(int i=0;s[i]!='\0';i++)      {          int d=s[i]-'a';          if(trie[x].child[d]==0)          {              trie[++trieN]=Node(); trie[x].child[d]=trieN;        }        x=trie[x].child[d];    } strcpy_s(trie[x].value,a);//把整个字符串[即字符串b]的信息[即字符串a]                        }                             //保存到字符串的最后一个字符中           void Serch(char s[]) //查找函数{      int x=0;      for(int i=0;s[i]!='\0';i++)      {          int d=s[i]-'a';          if(trie[x].child[d]==0)  //若字典并没有这个单词。        {              strcpy_s(temp,"eh");//按照题目要求返回"eh"return;        }          x=trie[x].child[d];      }  strcpy_s(temp,trie[x].value);  //若字典有这个单词,则把这个单词的信息返回}  int main()  {      char str[30],a[15],b[15],c[15];while(gets(str)&&str[0])//输入数据,把数据划分到a串和b串中 {int i=0,j;for(i=0;str[i]!=' ';i++){a[i]=str[i];}a[i]='\0';i++;for(j=0;str[i]!='\0';i++,j++){b[j]=str[i];}b[j]='\0';Insert(a,b);}    while(scanf_s("%s",c)!=EOF)    {            Serch(c);printf("%s\n",temp);    }      return 0;  } 

0 0