syhd142 |
|
|||
日歷
統計
導航常用鏈接留言簿(2)隨筆檔案(23)文章分類(270)
文章檔案(122)我的豆瓣搜索最新評論
閱讀排行榜
評論排行榜 |
模板題 #include <stdio.h>
#include <string.h> #include <math.h> #include <vector> #include <algorithm> #include <queue> using namespace std; #define KIND 128 #define M 10010 struct node { node *fail; node *next[KIND]; int id; node () { fail = NULL; id = 0; memset(next, 0, sizeof(next)); } }; char ch[M]; queue<node *> q; vector<int> g; void insert(node *&root, char *ch, int id) { node *p = root; int i = 0, t; while(ch[i]) { t = ch[i] - 31; if(!p->next[t]) p->next[t] = new node(); p = p->next[t]; i++; } p->id = id; } void AC(node *&root) { q.push(root); while(!q.empty()) { node *p = NULL; node *t = q.front(); q.pop(); for(int i = 0; i < KIND; i++) { if(t->next[i]) { p = t->fail; while(p) { if(p->next[i]) { t->next[i]->fail = p->next[i]; break; } p = p->fail; } if(!p) t->next[i]->fail = root; q.push(t->next[i]); } } } } bool query(node *&root, char *ch, int count) { g.clear(); int i = 0, t, top = 0, flag = 0; node *p = root, *tmp; while(ch[i]) { t = ch[i] - 31; while(!p->next[t] && p != root) p = p->fail; p = p->next[t]; if(!p) p = root; tmp = p; while(tmp != root && tmp->id) { flag = 1; g.push_back(tmp->id); tmp = tmp->fail; } i++; } if(!flag) return false; sort(g.begin(), g.end()); printf("web %d:", count); printf(" %d", g[0]); for(int i = 1; i < g.size(); i++) { if(g[i] != g[i - 1]) printf(" %d", g[i]); } printf("\n"); return true; } int main() { int n, total; while(~scanf("%d", &n)) { node *root = new node(); total = 0; for(int i = 0; i < n; i++) { scanf("%s", ch); insert(root, ch, i + 1); } AC(root); scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%s", ch); if(query(root, ch, i + 1)) total++; } printf("total: %d\n", total); } return 0; }
評論:
|
![]() |
|
Copyright © Fucker | Powered by: 博客園 模板提供:滬江博客 |