poj 2503 (trie)

  poj 2503

  题目链接poj 2503


 这道题目套用模板就差不多可以得到答案了。

 不过比较蛋疼的是输入。参考答案。


 模板  引用别人的模板点击打开链接


include <iostream>
using namespace std;
 
const int branchNum = 26; //声明常量 
int i;
 
struct Trie_node
<span style="font-family: Arial, Helvetica, sans-serif;">{</span>
    bool isStr; //记录此处是否构成一个串。
    Trie_node *next[branchNum];//指向各个子树的指针,下标0-25代表26字符
    Trie_node():isStr(false)
    {
        memset(next,NULL,sizeof(next));
    }
};

class Trie
{
public:
    Trie();
    void insert(const char* word);
    bool search(char* word); 
    void deleteTrie(Trie_node *root);
private:
    Trie_node* root;
};

Trie::Trie()
{
    root = new Trie_node();
}

void Trie::insert(const char* word)
{
    Trie_node *location = root;
    while(*word)
    {
        if(location->next[*word-'a'] == NULL)//不存在则建立
        {
            Trie_node *tmp = new Trie_node();
            location->next[*word-'a'] = tmp;
        }    
        location = location->next[*word-'a']; //每插入一步,相当于有一个新串经过,指针要向下移动
        word++;
    }
    location->isStr = true; //到达尾部,标记一个串
}

bool Trie::search(char *word)
{
    Trie_node *location = root;
    while(*word && location)
    {
        location = location->next[*word-'a'];
        word++;
    }
    return(location!=NULL && location->isStr);
}


再稍微变形一下 就可以得到答案


#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace std;
int nodenum;
struct trie_node
{
   bool isstr;
   trie_node *branch[26];
   char string[15];
}Node[1000010];

class trie
{
public:
  trie_node root;
  trie() { root=Node[0];}
  void insert(char s1[],char s2[] )
  {
      trie_node *location=&root;
      int i=0;
      while( s2[i] )
      {
         int tmp=s2[i]-'a';
         if(location->branch[tmp]==NULL)
         {
             location->branch[tmp]=&Node[nodenum] ;
             Node[nodenum].isstr=0;
             memset( Node[nodenum].branch,NULL,sizeof(Node[nodenum].branch) );
             nodenum++;
         }
         i++;
         location=location->branch[tmp];
       }
       location->isstr=1;
       strcpy( location->string, s1) ;
   }
   void search(char *word)
   {
       trie_node *location=&root;
       while(*word&&location)
       {
           location=location->branch[*word-'a'];
           word++;
       }
       if(location!=NULL&&location->isstr)
          cout<<location->string<<endl;
       else
          cout<<"eh"<<endl;
   }
};
int main()
{
   char s1[15],s2[15],s[40];
   nodenum=0;
   trie t;
   while(gets(s)&&s[0]!=0)
   {
       int i,j;
       for(i=0;s[i]!=' ';i++)
          s1[i]=s[i];
       s1[i]='\0';
       for(j=0,i+=1;s[i];i++,j++)
          s2[j]=s[i];
        s2[j]='\0';
        t.insert(s1,s2);
   }
   while(scanf("%s",s1)!=EOF)
        t.search(s1);

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值