hdu 2222 DFA 模板题

真心对此题无奈了。。。。配得上2222这个称号了
题目要求我们算出一个字符串中包含着多少个他给出的单词。
坑爹的是这单词居然有一样的。。。。
如果一样的两个单词被给出,那么答案就应该是2,而不是1
样例如下:
Sample Input:
1
5
ab
ab
ab
ab
ab
ab

Sample Output:
5

有种被骗的赶脚~

#include
#include
#include
#include
using namespace std;
#define Maxn 6010000

struct nodes {
    nodes * next[26], *fail; //fail 指针指向该节点的最长后缀
    int no, inde;
} D[Maxn], *Q[Maxn];
int tot;

nodes *newnodes() {
    memset(D[tot].next, 0, sizeof (int) *26);
    D[tot].no = 0;
    D[tot].inde = tot;
    return &D[tot++];
}

int code(char c) {
    return c - 'a';
}

void insert(char s[], nodes *p, int inp) {
    for (int i = 0; s[i]; i++) {
        int tmp = code(s[i]);
        if (p->next[tmp]) {
            p = p->next[tmp];
        } else {
            p->next[tmp] = newnodes();
            p = p->next[tmp];
        }
    }
    p->no += inp;
}

void buildAC(nodes *p) {
    int L = 0, R = 0, i;
    for (i = 0; i < 26; i++) {
        if (p->next[i]) {
            Q[R++] = p->next[i];
            p->next[i]->fail = p;
        } else {
            p->next[i] = p;
        }
    }
    while (L < R) {
        p = Q[L++];
        for (i = 0; i < 26; i++) {
            if (p->next[i]) {
                p->next[i]->fail = p->fail->next[i]; //p->next[i]的fail是p的fail的next[i];
                Q[R++] = p->next[i];
            } else p->next[i] = p->fail->next[i]; //p->next[i]一定不为空.
        }
    }
}
char st[1000500];
bool mark[10505];

int main() {
    int N, i, cas;
    scanf("%d", &cas);
    while (cas--) {
        memset(mark, false, sizeof (mark));
        char str[90];
        scanf("%d", &N);
        tot = 0;
        nodes *root = newnodes();
        for (i = 0; i < N; i++) {
            scanf("%s", str);
            insert(str, root, 1);
            mark[i] = false;
        }
        buildAC(root);
        scanf("%s", st);
        nodes *p = root;
        nodes *g;
        int ans = 0;
        for (i = 0; st[i]; i++) {
            int tmp = code(st[i]);
            p = p->next[tmp];
            if (p->no != 0)
                ans += p->no;
            p->no = 0;
            g = p;
            while (g->inde != 0) {
                g = g->fail;
                if (g->no != 0)
                    ans += g->no;
                g->no = 0;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值