• 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]='';     //strncpy中,word[i]代表复制的字符串起始位置,j+1代表要复制的长度
    55             strncpy(s2,word[i]+j+1,len-j-1),s2[len-j-1]='';   //后一段字符串
    56             if(search(s1)&&search(s2)){
    57                 printf("%s
    ",word[i]);
    58                 break;
    59             }
    60         }
    61     }
    62     //delete(root);
    63 }

    2018-10-29

  • 相关阅读:
    nyist_21(三个水杯)(BFS)
    寒假刷题之普通之红与黑
    寒假刷题之普通之变形课
    寒假刷题之普通之最小差
    什么是 Spring Boot
    择业十诫----与内心的渴望同行
    模式窗体中调用父页面Javascript
    二级域名解析
    软件测试
    网狐系统介绍
  • 原文地址:https://www.cnblogs.com/00isok/p/9874113.html
Copyright © 2020-2023  润新知