1. 程式人生 > >「Luogu4173」&&「BZOJ4529」殘缺的字串-FFT

「Luogu4173」&&「BZOJ4529」殘缺的字串-FFT

Description

給定兩個具有萬用字元的串 A A , B B 。其中 A A

是模板串,求匹配數。

Solution

考慮沒有萬用字元怎麼匹配,即從起始位置開始每個字元都相同,即 i = a a

+ T 1 ( s i
t i a ) 2 = 0 \sum_{i=a}^{a+|T|-1}(s_i-t_{i-a})^2=0

而萬用字元可以與任何字元相同,相當於乘上了 0 0 ,即 i = a a + T 1 p s , i p t , i a ( s i t i a ) 2 = 0 \sum_{i=a}^{a+|T|-1}p_{s,i}p_{t,i-a}(s_i-t_{i-a})^2=0 p s , i p_{s,i} 表示 s i s_i 是否是萬用字元。

反轉 S S 串,把式子拆開就是卷積的形式,FFT即可。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 300005 * 5;

int m, n;
char s[maxn], t[maxn];
int a[maxn], b[maxn], c[maxn], ans[maxn], Ans;

inline int gi()
{
    char c = getchar();
    while (c < '0' || c > '9') c = getchar();
    int sum = 0;
    while ('0' <= c && c <= '9') sum = sum * 10 + c - 48, c = getchar();
    return sum;
}

namespace FFT
{
    const double pi = acos(-1);
    typedef complex<double> cpx;
    
    int n, len, L, R[maxn];
    cpx A[maxn], B[maxn];
    
    void FFT(cpx *a, int f)
    {
        for (int i = 0; i < n; ++i) if (i < R[i]) swap(a[i], a[R[i]]);
        for (int i = 1; i < n; i <<= 1) {
            cpx wn(cos(pi / i), sin(f * pi / i)), t;
            for (int j = 0; j < n; j += (i << 1)) {
                cpx w(1, 0);
                for (int k = 0; k < i; ++k, w *= wn) {
                    t = a[j + i + k] * w;
                    a[j + i + k] = a[j + k] - t;
                    a[j + k] = a[j + k] + t;
                }
            }
        }
    }

    void mul(int *a, int *b, int len1, int len2, int *c)
    {
        L = 0;
        for (n = 1, len = len1 + len2 - 1; n < len; n <<= 1) ++L;
        --L;
        for (int i = 0; i < n; ++i) R[i] = (R[i >> 1] >> 1) | ((i & 1) << L);

        fill(A, A + n, 0); fill(B, B + n, 0);
        for (int i = 0; i < len1; ++i) A[i] = a[i];
        for (int i = 0; i < len2; ++i) B[i] = b[i];

        FFT(A, 1); FFT(B, 1);
        for (int i = 0; i < n; ++i) A[i] *= B[i];
        FFT(A, -1);

        for (int i = 0; i < len2; ++i) c[i] = (int)(A[i].real() / n + 0.5);
    }

}
    
int main()
{
    m = gi(); n = gi();
    scanf("%s\n", s); reverse(s, s + m);
    scanf("%s\n", t);

    for (int i = 0; i < m; ++i) a[i] = (s[i] != '*') * (s[i] - 'a') * (s[i] - 'a');
    for (int i = 0; i < n; ++i) b[i] = (t[i] != '*');
    FFT::mul(a, b, m, n, c);
    for (int i = 0; i < n; ++i) ans[i] += c[i];
    
    for (int i = 0; i < m; ++i) a[i] = (s[i] != '*');
    for (int i = 0; i < n; ++i) b[i] = (t[i] != '*') * (t[i] - 'a') * (t[i] - 'a');
    FFT::mul(a, b, m, n, c);
    for (int i = 0; i < n; ++i) ans[i] += c[i];

    for (int i = 0; i < m; ++i) a[i] = (s[i] != '*') * (s[i] - 'a');
    for (int i = 0; i < n; ++i) b[i] = (t[i] != '*') * (t[i] - 'a');
    FFT::mul(a, b, m, n, c);
    for (int i = 0; i < n; ++i) ans[i] -= c[i] * 2;

    for (int i = m - 1; i < n; ++i) if (!ans[i]) ++Ans;
    printf("%d\n", Ans);
    for (int i = m - 1; i < n; ++i) if (!ans[i]) printf("%d ", i - m + 2);
    
    return 0;
}