Codeforces 235C

本文介绍了解决Codeforces235C问题的方法,使用后缀自动机(SAM)处理字符串匹配,通过构建SAM并进行特殊处理,解决了询问串的所有循环移位串在主串中出现次数的问题。

Codeforces 235C


题目:给定一主串\(S\)\(n\)次询问,每次询问串\(t\)的所有循环移位串的出现的次数和

做法:建\(SAM\),对于询问串\(t\),将他复制一份放在后边,在后缀自动机上匹配,如果匹配长度大于\(|t|\),就沿着\(fa\), 找到第一次大于\(|t|\)的位置,用这个状态的\(right\)数组更新答案。注意到可能会匹配到重复的状态,所以要对会更新答案的状态去重。

#include <bits/stdc++.h>
typedef long long ll;
const int N = 1000010 << 1;
using namespace std;

struct SAM{
    int n, step[N], fa[N], ch[N][26], right[N], num[N], last, root, cnt;
    char s[N>>1];
    SAM(){last = root = ++cnt; }
    void add(int x){
        int tmp = s[x] - 'a', p = last, np = ++cnt;
        step[last = np] = x, right[np] = 1;
        while(p && !ch[p][tmp]) ch[p][tmp] = np, p = fa[p];
        if(!p) fa[np] = root;
        else{
            int q = ch[p][tmp];
            if(step[q] == step[p] + 1) fa[np] = q;
            else{
                int nq = ++cnt; step[nq] = step[p] + 1;
                memcpy(ch[nq], ch[q], sizeof(ch[q]));
                fa[nq] = fa[q], fa[q] = fa[np] = nq;
                while(ch[p][tmp] == q) ch[p][tmp] = nq, p = fa[p];
            }
        }
    }
    int tmp[N];
    void calright(){
        memset(tmp, 0, sizeof(tmp));
        for(int i = 1; i <= cnt; i++) tmp[step[i]]++;
        for(int i = 1; i <= n; i++) tmp[i] += tmp[i - 1];
        for(int i = cnt; i; i--) num[tmp[step[i]]--] = i;
        for(int i = cnt; i; i--) right[fa[num[i]]] += right[num[i]];
    }
    void run(){
        scanf(" %s",s+1), n = strlen(s + 1);
        for(int i = 1; i <= n; i++) add(i);
        calright();
    }

    char str[N];
    int len;
    set<int> S;
    ll solve() {
        scanf(" %s",str+1), len = strlen(str+1);
        for(int i = 1; i <= len; ++i) str[i+len] = str[i];
        int now = root, tmp = 0; ll ans = 0;
        for(int i = 1; i <= len+len; ++i) {
            int x = str[i]-'a';
            if(ch[now][x]) now = ch[now][x], ++tmp;
            else {
                while(now && !ch[now][x]) now = fa[now];
                if(!now) now = root, tmp = 0;
                else tmp = step[now]+1, now = ch[now][x];
            }
            while(now!=1 && step[fa[now]] >= len) now = fa[now], tmp = step[now];
            if(tmp >= len) S.insert(now);
        }
        for(set<int>::iterator it = S.begin(); it != S.end(); ++it) ans += right[*it];
        S.clear();
        return ans;
    }
} Fe;

int main() {
    Fe.run();
    int q;
    scanf("%d",&q);
    while(q--) {
        printf("%I64d\n",Fe.solve());
    }
}

转载于:https://www.cnblogs.com/RRRR-wys/p/10299830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值