AC自动机
1 /* 2 AC自动机模板 3 */ 4 struct AC { 5 int ch[MAXNODE][SIZE], fail[MAXNODE], val[MAXNODE], sz; 6 void init(void) { 7 memset (ch[0], 0, sizeof (ch[0])); 8 sz = 1; val[0] = 0; 9 } 10 int idx(char c) { 11 return c - ‘a‘; 12 } 13 void insert(char *P) { 14 int u = 0; 15 for (int i=0; P[i]; ++i) { 16 int c = idx (P[i]); 17 if (!ch[u][c]) { 18 memset (ch[sz], 0, sizeof (ch[sz])); 19 ch[u][c] = sz; val[sz++] = 0; 20 } 21 u = ch[u][c]; 22 } 23 val[u]++; 24 } 25 void get_fail(void) { 26 queue<int> Q; fail[0] = 0; 27 for (int i=0; i<SIZE; ++i) { 28 int u = ch[0][i]; 29 if (u) { 30 fail[u] = 0; Q.push (u); 31 } 32 } 33 while (!Q.empty ()) { 34 int u = Q.front (); Q.pop (); 35 for (int i=0; i<SIZE; ++i) { 36 int &v = ch[u][i]; 37 if (!v) { 38 v = ch[fail[u]][i]; continue; 39 } 40 Q.push (v); 41 fail[v] = ch[fail[u]][i]; //val[v] += val[fail[u]]; 42 } 43 } 44 } 45 int query(char *T) { 46 int ret = 0; 47 for (int u=0, i=0; T[i]; ++i) { 48 int c = idx (T[i]); 49 u = ch[u][c]; 50 ret += val[u]; 51 int tmp = u; 52 while (tmp) { 53 ret += val[tmp]; val[tmp] = 0; 54 tmp = fail[tmp]; 55 } 56 } 57 return ret; 58 } 59 }ac;
时间: 2024-10-11 11:00:29