[关闭]
@lunar 2016-03-03T19:02:10.000000Z 字数 1379 阅读 1228

HiHo一下 Week4 Trie图

HiHo


输入

每个输入文件有且仅有一组测试数据。

每个测试数据的第一行为一个整数N,表示河蟹词典的大小。

接下来的N行,每一行为一个由小写英文字母组成的河蟹词语。

接下来的一行,为一篇长度不超过M,由小写英文字母组成的文章。

对于60%的数据,所有河蟹词语的长度总和小于10, M<=10

对于80%的数据,所有河蟹词语的长度总和小于10^3, M<=10^3

对于100%的数据,所有河蟹词语的长度总和小于10^6, M<=10^6, N<=1000

输出

对于每组测试数据,输出一行"YES"或者"NO",表示文章中是否含有河蟹词语。

样例输入

6
aaabc
aaac
abcc
ac
bcd
cd
aaaaaaaaaaabaaadaaac

样例输出

YES

思路

代码

  1. #include<iostream>
  2. #include<cstring>
  3. #include<queue>
  4. using namespace std;
  5. #define MAX 26
  6. struct Trie{
  7. int cnt;
  8. Trie *fail;
  9. Trie *next[MAX];
  10. Trie(){
  11. cnt = 0;
  12. for(int i=0;i<MAX;i++) next[i] = NULL;
  13. }
  14. };
  15. //build Trie Tree
  16. void build(Trie *root,char *c){
  17. Trie *p=root;
  18. int pos;
  19. while(*c){
  20. pos = *c - 'a';
  21. if(p->next[pos]==NULL) p->next[pos]= new Trie();
  22. p = p->next[pos];
  23. c++;
  24. }
  25. p->cnt++;
  26. }
  27. //Swith Trie Tree to Trie Graph
  28. void TrieG(Trie *root){
  29. queue <Trie *>q;
  30. root->fail=root;
  31. for(int i=0;i<MAX;i++){
  32. if(root->next[i]==NULL) root->next[i] = root;
  33. else{
  34. root->next[i]->fail = root;
  35. q.push(root->next[i]);
  36. }
  37. }
  38. while(!q.empty()){
  39. Trie *temp =q.front();
  40. q.pop();
  41. if((temp->fail->cnt >0)&&(temp->cnt==0))temp->cnt++;
  42. for(int i=0;i<MAX;i++){
  43. if(temp->next[i]==NULL) temp->next[i] = temp->fail;
  44. else{
  45. temp->next[i]->fail = temp->fail->next[i];
  46. q.push(temp->next[i]);
  47. }
  48. }
  49. }
  50. }
  51. int main()
  52. { int n;
  53. bool flag = false;
  54. char words[1000000];
  55. Trie *root = new Trie();
  56. cin >> n;
  57. while(n--){
  58. cin>> words;
  59. build(root,words);
  60. }
  61. TrieG(root);
  62. char *s;
  63. cin >> words;
  64. s = words -1;
  65. Trie *temp = root;
  66. while(*++s){
  67. temp = temp->next[*s - 'a'];
  68. if(temp->cnt>0){
  69. flag = true;
  70. break;
  71. }
  72. }
  73. string out = flag ? "YES":"NO";
  74. cout << out;
  75. return 0;
  76. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注