MnZn 刚学 AC 自动机求助
查看原帖
MnZn 刚学 AC 自动机求助
420129
Nt_Tsumiki楼主2023/12/26 14:18

rt

正确性有问题,求调。

#include <unordered_map>
#include <iostream>
#include <cstdio>
#include <queue>
#include <list>

using namespace std;
int n,m,len,s[100001],ans1[50001],ans2[100001];
unordered_map<int,bool> mm[100001];
vector<int> l[100001];

int cnt,fail[200001];
vector<int> num[200001];
unordered_map<int,int> ch[200001];

void ins(int x) {
    int y=0;
    for (int i=1;i<=len;i++) {
        if (!ch[y].count(s[i])) ch[y][s[i]]=++cnt;
        y=ch[y][s[i]];
    }
    num[y].push_back(x);
}

void getfail() {
    queue<int> q;
    for (auto i:ch[0]) q.push(i.second);
    while (!q.empty()) {
        int x=q.front(); q.pop();
        for (auto i:ch[x]) fail[i.second]=ch[fail[x]][i.first],q.push(i.second);
    }
}

void ask(int x,int id) {
    int y=0,ty=0;
    for (auto i:l[x]) {
        while (!ch[y].count(i) and y) y=fail[y];
        if (ch[y].count(i)) y=ch[y][i];
        else y=0;
        ty=y;
        while (ty) {
            for (auto j:num[ty])
                if (!mm[j].count(id)) {
                    ans2[j]++,ans1[id]++;
                    mm[j][id]=1;
                }
            ty=fail[ty];
        }
    }
}

int main() {
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) {
        scanf("%d",&len);
        for (int j=1,x;j<=len;j++) {
            scanf("%d",&x);
            l[i*2-1].push_back(x);
        }
        scanf("%d",&len);
        for (int j=1,x;j<=len;j++) {
            scanf("%d",&x);
            l[i*2].push_back(x);
        }
    }
    for (int i=1;i<=m;i++) {
        scanf("%d",&len);
        for (int j=1;j<=len;j++) scanf("%d",s+j);
        ins(i);
    }
    getfail();
    // for (int i=0;i<=cnt;i++) printf("fail:%d\n",fail[i]);
    for (int i=1;i<=n;i++) ask(i*2-1,i),ask(i*2,i);
    // printf("%d\n",ans2[0]);
    for (int i=1;i<=m;i++) printf("%d\n",ans2[i]);
    for (int i=1;i<=n;i++) printf("%d ",ans1[i]);
    return 0;
}
/*
2 3
6 8 25 0 24 14 8 6 18 0 10 20 24 0
7 14 17 8 7 0 17 0 5 8 25 0 24 0
4 8 25 0 24
4 7 0 17 0
4 17 0 8 25

*/
2023/12/26 14:18
加载中...