HDU 2222
这题应该是用输入的模式串应该是可以有多个相同的,所以有count++,而且有一个地方是
if(temp->count>0) //>0是必须的。
{
cnt+=temp->count;
temp->count=0;
}
temp=temp->fail;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | #include<stdio.h> #include<string.h> #include<malloc.h> #include<queue> using namespace std; char str[1000000+100]; struct node { int count; struct node *next[26]; struct node *fail; void init() { int i; for (i=0;i<26;i++) next[i]=NULL; count=0; fail=NULL; } }*root; void insert() { int len,k; node *p=root; len= strlen (str); for (k=0;k<len;k++) { int pos=str[k]- 'a' ; if (p->next[pos]==NULL) { p->next[pos]= new node; p->next[pos]->init(); p=p->next[pos]; } else p=p->next[pos]; } p->count++; } void getfail() { int i; node *p=root,*son,*temp; queue< struct node *>que; que.push(p); while (!que.empty()) { temp=que.front(); que.pop(); for (i=0;i<26;i++) { son=temp->next[i]; if (son!=NULL) { if (temp==root) {son->fail=root;} else { p=temp->fail; while (p) { if (p->next[i]) { son->fail=p->next[i]; break ; } p=p->fail; } if (!p) son->fail=root; } que.push(son); } } } } void query() { int len,i,cnt=0; len= strlen (str); node *p,*temp; p=root; for (i=0;i<len;i++) { int pos=str[i]- 'a' ; while (!p->next[pos]&&p!=root) p=p->fail; p=p->next[pos]; if (!p) p=root; temp=p; while (temp!=root) { if (temp->count>0) { cnt+=temp->count; temp->count=0; } temp=temp->fail; } } printf ( "%d\n" ,cnt); } int main() { int cas,n; scanf ( "%d" ,&cas); while (cas--) { root= new node; root->init(); root->fail=NULL; scanf ( "%d" ,&n); int i; getchar (); for (i=0;i<n;i++) { gets (str); insert(); } getfail(); gets (str); query(); } return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步