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

<题目链接>

题目大意:

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

解题分析:

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

 #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int M = 5e4+;
char word[M][]; struct Node{
bool flag;
Node *next[];
Node(){
flag=false;
for(int i=;i<;i++)
next[i]=NULL;
}
};
Node *root=new Node;
Node *now,*newnode;
void Insert(char *str){
now=root;
for(int i=;str[i];i++){
int to=str[i]-'a';
if(now->next[to]==NULL){
now->next[to]=new Node;
}
now=now->next[to];
}
now->flag=true; //标记该节点为单词的结尾
}
bool search(char *str){
now=root;
for(int i=;str[i];i++){
int to = str[i]-'a';
if(now->next[to]==NULL)return false;
now=now->next[to];
}
return now->flag;
}
void delete(Node *rt){
for(int i=;i<;i++)
if(rt->next[i]!=NULL)
delete(rt->next[i]);
delete(rt);
}
int main(){
int cnt=;
while(gets(word[++cnt])&&strlen(word[cnt]))
Insert(word[cnt]);
for(int i=;i<=cnt;i++){
int len=strlen(word[i]);
for(int j=;j<len;j++){
char s1[],s2[];
strncpy(s1,word[i],j+),s1[j+]='\0'; //strncpy中,word[i]代表复制的字符串起始位置,j+1代表要复制的长度
strncpy(s2,word[i]+j+,len-j-),s2[len-j-]='\0'; //后一段字符串
if(search(s1)&&search(s2)){
printf("%s\n",word[i]);
break;
}
}
}
//delete(root);
}

2018-10-29

上一篇:HDU1247 Hat’s Words 【trie树】


下一篇:[译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了