HDU-1247 Hat’s Words (暴力)【Trie树】

<题目链接>

题目大意:

给你一些单词,要求输出将该单词完全分成前、后两个单词之后,若这两个单词都在单词库中出现,则输出该单词。

解题分析:

将每个单词的每一位能够拆分的位置全部暴力枚举一遍,若拆分后的两个单词都在单词库中,则直接输出该单词即可,拆分单词的时候用strncpy()函数比较方便。

 

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 const int M = 5e4+10;
 7 char word[M][100];
 8 
 9 struct Node{
10     bool flag;
11     Node *next[26];
12     Node(){
13         flag=false;
14         for(int i=0;i<26;i++)
15             next[i]=NULL;
16     }
17 };
18 Node *root=new Node;
19 Node *now,*newnode;
20 void Insert(char *str){
21     now=root;
22     for(int i=0;str[i];i++){
23         int to=str[i]-'a';
24         if(now->next[to]==NULL){
25             now->next[to]=new Node;
26         }
27         now=now->next[to];
28     }
29     now->flag=true;    //标记该节点为单词的结尾
30 }
31 bool search(char *str){
32     now=root;
33     for(int i=0;str[i];i++){
34         int to = str[i]-'a';
35         if(now->next[to]==NULL)return false;
36         now=now->next[to];
37     }
38     return now->flag;
39 }
40 void delete(Node *rt){
41     for(int i=0;i<26;i++)
42         if(rt->next[i]!=NULL)
43             delete(rt->next[i]);
44     delete(rt);
45 }
46 int main(){
47     int cnt=0;
48     while(gets(word[++cnt])&&strlen(word[cnt]))
49         Insert(word[cnt]);
50     for(int i=1;i<=cnt;i++){
51         int len=strlen(word[i]);
52         for(int j=0;j<len;j++){
53             char s1[110],s2[110];
54             strncpy(s1,word[i],j+1),s1[j+1]='\0';     //strncpy中,word[i]代表复制的字符串起始位置,j+1代表要复制的长度
55             strncpy(s2,word[i]+j+1,len-j-1),s2[len-j-1]='\0';   //后一段字符串
56             if(search(s1)&&search(s2)){
57                 printf("%s\n",word[i]);
58                 break;
59             }
60         }
61     }
62     //delete(root);
63 }

 

 

 

2018-10-29

转载于:https://www.cnblogs.com/00isok/p/9874113.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值