hdu 1247 Hat’s Words

来源:互联网 发布:mac 命令行退出 编辑:程序博客网 时间:2024/05/16 01:48

/*字典树!

这道题还真是坑爹啊!

要查询是不是整个词是不是存在,只要判断最后一位是不是有记录!*/

#include <iostream>#include <stdio.h>#include <string.h>#include <math.h>#include <stdlib.h>#include <algorithm>#include <vector>#include <limits.h>#include <queue>#include <stack>using namespace std;struct trie{ int cnt; trie* next[26];};char str[50010][50];void inst(trie *root,char *s){ int i; trie* p = root; i = 0; while(s[i]!='\0') { int k = s[i]-'a'; if(p->next[k]==NULL) { trie *tmp = new trie; for(int j = 0;j < 26;j ++) tmp->next[j] = NULL; tmp->cnt = 0; p->next[k] = tmp; } //else p->cnt ++; p = p->next[k]; i ++; } p->cnt = 1;}bool search(trie* root,char *s){ int i = 0; bool f = 1; trie* p = root; //cout<<s<<endl; while(s[i]!='\0') { int k = s[i]-'a'; if(p->next[k]==NULL) return 0; else p = p->next[k]; i ++; } if(p->cnt == 1) return 1; else return 0;}int main(){ int i=0; trie *root = new trie; for(i = 0;i < 26;i ++) root->next[i] = NULL; root ->cnt = 0; i = 0; while(scanf("%s",str[i])!=EOF) { inst(root,str[i]); i ++; //if(i > 5 )break; } //sort(str,str+i,cmp2); for(int j = 0;j < i;j ++) { for(int l = 0;l < strlen(str[j]);l ++) { char temp1[50]={'\0'}; char temp2[50]={'\0'}; strncpy(temp1,str[j],l); strncpy(temp2,str[j]+l,strlen(str[j])-l); //cout<<temp1<<" "<<temp2<<endl; if(search(root,temp1)&&search(root,temp2)) { printf("%s\n",str[j]); break; } } }}

原创粉丝点击