Description
给定两个具有通配符的串 A A A, B B B。其中 A 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 ∑i=aa+∣T∣−1(si−ti−a)2=0。
而通配符可以与任何字符相同,相当于乘上了 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 ∑i=aa+∣T∣−1ps,ipt,i−a(si−ti−a)2=0。 p s , i p_{s,i} ps,i表示 s i s_i si是否是通配符。
反转 S 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;
}