poj 2001 trie 树

题意:求给出的字符串的最小前缀,此前缀满足是这些字符串中唯一的前缀,也就是这个前缀除了这个字符串以外不能再是其它字符串的前缀了.

思路:trie

这道题让我明晰了  strncpy()这个函数,它是把第二个字符串的前n个字符附给第一个字符串,但是我输出的时候却错了,可能第n个字符没有被覆盖,后来在第一个字符串的n这个位置改成'\0'...果断水过.

#include<iostream>
#include<cstring>
using namespace std;
struct node
{
  int count;
  node *next[26];
  node()
  {
    count=0;
    for(int i=0;i<26;i++)
    next[i]=NULL;
  }
};
char s[30];
void insert(node *root,char *word)
{
  int i=0,branch;
  node *l=root;
  while(word[i]!='\0')
  {
    branch=word[i]-'a';
    if(l->next[branch]!=NULL) 
    {
      l->next[branch]->count++;
      //printf("insertcount=%d\n",l->next[branch]->count);
    }
    else l->next[branch]=new node();
    l=l->next[branch];
    i++;
  }
}
int search(node *root,char *word)
{
  int i=0,branch,ans;
  node *l=root;
  while(word[i]!='\0')
  {
    branch=word[i]-'a';
    if(l->next[branch]!=NULL)
    {
      //printf("count=%d\n",l->next[branch]->count);
      l=l->next[branch];
      if(l->count==0)
      {ans=i;break;}
    }
    i++;
  }
  if(word[i]=='\0') strcpy(s,word); 
  else  
  {strncpy(s,word,ans+1);s[ans+1]='\0';}
  return 0;
}
int main()
{
  char word[30];
  char str[1010][30];
  node *root=new node();
  int i=0;
  freopen("data.txt","r",stdin);
  freopen("shuchu.txt","w",stdout);
  while(gets(word))
  {
    strcpy(str[i],word);
    insert(root,word);
    i++;
  }
  for(int j=0;j<i;j++)
  {
    //printf("search=%s\n",str[j]);
    search(root,str[j]);
    printf("%s %s\n",str[j],s);
  }
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值