PKU2001

这个是个trie树的超简单题了,要注意的是trie树中由于根中逻辑上没有元素,仅起一个引导搜索的作用,所以要比实际的字符串位置快了一步。

 

题目链接:http://poj.org/problem?id=2001 

#include <stdio.h>
#include <string.h>

struct trie_node
{
 int num;
 trie_node* branch[26];
 
 trie_node()
 {
  num = 0;
  int i;
  for(i = 0;i < 26;++i)
   branch[i] = NULL;
 }
};

struct trie
{
 trie_node* root;
 
 trie(){root = NULL;}
 
 void insert(const char* word)
 {
  if(root == NULL)
   root = new trie_node();

  trie_node* cur = root;
  while(*word)
  {
   int pos = *word - 'a';
   if(cur->branch[pos] == NULL)
    cur->branch[pos] = new trie_node();
   ++cur->branch[pos]->num;
   cur = cur->branch[pos];
   ++word;
  }
 }

 void prefix(const char* word)
 {
  trie_node* cur = root;
  while(cur != NULL && *word)
  {
   if(cur->num == 1)
   {
    printf("\n");
    return;
   }

   printf("%c",*word);

   int pos = *word - 'a';
   cur = cur->branch[pos];
   ++word;
  }

  printf("\n");
 }
};

int main()
{
 freopen("in.txt","r",stdin);

 trie tree;
 char strs[1000][21];
 int i = 0;
 while(scanf("%s",strs[i]) != EOF)
 {
  tree.insert(strs[i]);
  ++i;
 }

 int j = 0;
 while(j < i)
 {
  printf("%s ",strs[j]);
  tree.prefix(strs[j]);
  ++j;
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值