ac自动机背诵用模板

来源:互联网 发布:时时彩网站源码 编辑:程序博客网 时间:2024/05/17 22:47
struct ac {
    node *fail; 
    node * xia[26];
    int ci; 

   ac() { 
        fail = NULL;
        ci= 0;
        memset(xia, NULL, sizeof (xia));
    }
} *q[500001]; 
char s1[51];
char str[1000001]; 
int zhen1,zhen2; 

void insert(char *str, ac *root) {
    ac *p = root;
    int i = 0, zimu;
    while (str[i]) {
        zimu = str[i] - 'a';
        if (p->xia[zimu] == NULL)
            p->xia[zimu] = new ac();
        p = p->xia[zimu];
        i++;
    }
    p->ci++;
}

void shipei(ac *root) {
    int i;
    root->fail = NULL;
    q[zhen1++] = root;
    while (zhen1 != zhen2) {
        ac *now = q[zhen2++];
        ac *p = NULL;
        for (i = 0; i < 26; i++) {
            if (now->xia[i] != NULL) {
                if (now == root)
                    now->xia[i]->fail = root;
                else {
                    p = now->fail;
                    while (p != NULL) {
                        if (p->xia[i] != NULL) {
                            now->xia[i]->fail = p->xia[i];
                            break;
                        }
                        p = p->fail;
                    }
                    if (p == NULL)
                        now->xia[i]->fail = root;
                }
                q[zhen1++] = now->xia[i];
            }
        }
    }
}

int zhao(ac *root) {
    int i = 0, cnt = 0, zimu, len = strlen(str);
    ac *p = root;
    while (str[i]) {
        zimu = str[i] - 'a';
        while (p->xia[zimu] == NULL && p != root) p = p->fail;
        p = p->xia[zimu];
        p = (p == NULL) ? root : p;
        ac *now = p;
        while (now != root && now->ci != -1) {
            cnt += now->ci;
            now->ci= -1;
            now= now->fail;
        }
        i++;
    }
    return cnt;
}

int main() {
    int n, t;
    scanf("%d", &t);
    while (t--) {
        zhen1 = zhen2 = 0;
      ac *root = new ac();
        scanf("%d", &n);
        getchar();
        while (n--) {
            gets(s1);
            insert(s1, root);
        }
        shipei(root);
        scanf(" %s", str);
        printf("%d\n", zhao(root));
        int a[100];
        memset(a, 0, sizeof (a));
    }
    return 0;
}
注意:失配函数全是!=NULL而不是root;


0 0