Pagini recente » Cod sursa (job #1419432) | Cod sursa (job #2561365) | Cod sursa (job #259756) | Cod sursa (job #63195) | Cod sursa (job #104383)
Cod sursa(job #104383)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTEXT 10000000
#define MAXLEN 20
#define MAXWORDS 50000
#define MAXNODES (MAXWORDS * MAXLEN + 1)
#define CHARSET 3
int next[MAXNODES][CHARSET], f[MAXNODES], q[MAXNODES], queue[MAXNODES], nodes;
char text[MAXTEXT + 1];
void trie_init() {
nodes = 1;
}
void trie_add(char *word) {
char *p;
int t, ch;
for(p = word, t = 1; *p; p++) {
ch = *p - 'a';
if(!next[t][ch]) next[t][ch] = ++nodes;
t = next[t][ch];
}
q[t] = 1;
}
void build_failure() {
int i, j, k, ql, qr;
ql = qr = 0;
for(i = 0; i < CHARSET; i++) {
if(next[1][i]) {
f[next[1][i]] = 1;
queue[qr++] = next[1][i];
} else {
next[1][i] = 1;
}
}
while(ql < qr) {
i = queue[ql++];
for(j = 0; j < CHARSET; j++) {
if(!next[i][j]) continue;
queue[qr++] = next[i][j];
k = f[i];
while(!next[k][j]) k = f[k];
f[next[i][j]] = next[k][j];
q[next[i][j]] += q[next[k][j]];
}
}
}
// Aho-Corasick set matching
int solve() {
char *p;
int t, ch, count;
count = 0;
t = 1;
for(p = text; *p; p++) {
ch = *p - 'a';
while(!next[t][ch]) t = f[t];
t = next[t][ch];
count += q[t];
}
return count;
}
int main() {
char word[MAXLEN + 1];
freopen("abc2.in", "rt", stdin);
freopen("abc2.out", "wt", stdout);
gets(text);
trie_init();
while(gets(word)) trie_add(word);
build_failure();
printf("%d\n", solve());
return 0;
}