洛谷 P2336 AC自动机 + 暴力

       给你 n n n 个猫的两个字符串,点 m m m 次名,当点名为该猫的的子串时,猫猫答到。问,每次点名,几只猫答到。 m m m 次点名后,每只猫答到几次。

       两个坑点,1.点到只算一次,所以我们要用分隔符将他隔开,将并在一起同时查询。2.字符串的字符种类多达1e4种,所以我们要开 m a p map map 优化,把字符 h a s h hash hash 一下。并通过迭代器迭代 m a p map map

       思路:我们暴力的去找主串含有哪些模式串后缀,记录点名次数,通过简单的映射就可以知道最后的每个点名的答道猫数。同时每次暴力找返回猫的被点次数。用个 v i s vis vis 数组防止一只猫被同次点名点多次。由于用 m a p map map 构造 f a i l fail fail 树,所以我们要手动跳 f a i l fail fail 指针。

       注:这个貌似是因为数据弱,所以能过,正解应当是后缀数组或者 S A M SAM SAM

       代码如下:

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 5;
int cnt;
unordered_map<int, int> tr[maxn];
int isend[maxn], fail[maxn];
int ans[maxn], num[maxn], id[maxn], vis[maxn];
vector<int> text[maxn];
queue<pair<int, int> > rev;
int mo[maxn];

void insert(int s[], int lens, int no){
    int p = 0, k;
    for(int i = 1; i <= lens; i++){
        k = s[i];
        if(!tr[p][k]) tr[p][k] = ++cnt;
        p = tr[p][k];
    }
    isend[p]++;
    id[no] = p;
}

void build(){
    queue<int> q;
    for(auto u : tr[0])q.push(u.second);
    while(!q.empty()){
        int k = q.front();
        q.pop();
        for(auto u : tr[k]){
            int t = u.first, fa = fail[k];
            while(fa && !tr[fa].count(t)) fa = fail[fa];    // 手动跳fail
            fail[u.second] = tr[fa][t];
            q.push(u.second);
        }
    }
}

int query(vector<int> t, int no){
    int sum = 0;
    for(int i = 0, p = 0; i < t.size(); i++){
        while(p && !tr[p].count(t[i]))  p = fail[p];    // 手动跳fail
        p = tr[p][t[i]];
        for(int j = p; j; j = fail[j]){
            if(isend[j]){
                if(vis[j] == no)break;
                vis[j] = no;
                sum += isend[j];
                num[j]++;
            }
        }
    }
    return sum;
}

int main(){
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    int n, m, lens, x;
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> lens;
        for(int j = 0; j < lens; j++){
            cin >> x;
            text[i].push_back(x);
        }
        text[i].push_back(10001);      // 分隔符
        cin >> lens;
        for(int j = 0; j < lens; j++){
            cin >> x;
            text[i].push_back(x);
        }
    }
    for(int i = 1; i <= m; i++){
        cin >> lens;
        for(int j = 1; j <= lens; j++)
            cin >> mo[j];
        insert(mo, lens, i);
    }
    build();
    for(int i = 1; i <= n; i++)
        ans[i] = query(text[i], i);
    for(int i = 1; i <= m; i++)
        cout << num[id[i]] << endl;
    for(int i = 1; i <= n; i++)
        cout << ans[i] << " ";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值