poj 2503 Babelfish trie树!!!!指针版和数组版 基础

指针版

 #include<iostream>
using namespace std;
#define max 26
struct node//初始tire树
{
 bool boo;//判断是否是字符串最低端
 char aa[15];//将b字符串最低端 存a字符串
 node *next[max];
};
node *root;
void trie()//初始!!!!
{
 root=new node;
 root->boo=0;
 for(int i=0;i<max;i++)
 root->next[i]=NULL;
}
void insert(char a[],char b[])
{
 node *p=root,*t;//将p指向当前节点,p来开辟内存
 int len=strlen(b);//
 for(int i=0;i<len;i++)//建立b字符串这么深得树
 {
  if(p->next[b[i]-'a']==NULL)
  {
   t=new node;
   for(int j=0;j<max;j++)
   t->next[j]=NULL;
   t->boo=0;
   p->next[b[i]-'a']=t;
  }
  p=p->next[b[i]-'a'];
 }
 p->boo=1;//树低用boo标记
 memcpy(p->aa,a,sizeof(p->aa));//把a字符串存入树低
}
void search(char c[])
{
 int len=strlen(c);
 node *p=root;
 for(int i=0;i<len;i++)//按树查找,如果到了树低boo值为1,就将字符aa输出
 {
  if(p->next[c[i]-'a']!=NULL)
  p=p->next[c[i]-'a'];
  else
  {
   printf("eh\n");
   return ;
  }
 }
 if(p->boo==1)
 printf("%s\n",p->aa);
 else
 printf("eh\n");
}
  
int main()
{
 
 char a[15],b[15],c[15];
 trie();
 while(scanf("%s",a)&&getchar()==' ')//这个格式真让人纠结
    {
        scanf("%s",b);
        insert(a,b);
    }
 do
 {
  search(a);
 }
 while(scanf("%s",a)!=EOF);
 return 0;
}
 
数组版

#include<stdio.h>
#include<string.h>
struct trie
{
    int boo;
    char node [15];
    int son[27];
}tree[150010];
int num;
void insert(char a[],char b[])
{
    int now=0;
    for(int i=0;i<strlen(b);i++)
    {
        if(tree[now].son[b[i]-'a']==-1)
        {
            num++;
            for(int t=0;t<26;t++)
                tree[num].son[t]=-1;
            tree[num].boo=0;
            tree[now].son[b[i]-'a']=num;/*i wrote the son as 'A' at the first time*/
        }
        now=tree[now].son[b[i]-'a'];
    }
    memcpy(tree[now].node,a,sizeof(tree[now].node));
    tree[now].boo=1;
}
int find(char temp[])
{
    int now=0;
    for(int i=0;i<strlen(temp);i++)
    {
        now=tree[now].son[temp[i]-'a'];
        if(now==-1)
            return 0;
    }
    if(tree[now].boo)
    {
        printf("%s\n",tree[now].node);
        return 1;
    }
    return 0;   
}
int main()
{
    for(int i=0;i<26;i++)
        tree[0].son[i]=-1;  
    char a[15],b[15];
    while(scanf("%s",a)&&getchar()==' ')
    {
        scanf("%s",b);
        insert(a,b);
    }
    do
    {
        if(find(a)==0)
        printf("eh\n");
    }
    while(scanf("%s",a)!=EOF);
        return 0;
}
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码随想录

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值