隐藏
「bzoj4259」残缺的字符串 - 带通配符字符串匹配/FFT | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「bzoj4259」残缺的字符串 - 带通配符字符串匹配/FFT

题目大意

    很久很久以前,在你刚刚学习字符串匹配的时候,有两个仅包含小写字母的字符串$A$和$B$,其中$A$串长度为$m$,$B$串长度为$n$。可当你现在再次碰到这两个串时,这两个串已经老化了,每个串都有不同程度的残缺。
    你想对这两个串重新进行匹配,其中$A$为模板串,那么现在问题来了,请回答,对于$B$的每一个位置$i$,从这个位置开始连续$m$个字符形成的子串是否可能与$A$串完全匹配?


题目分析

照搬kls的做法,却因卡常惨遭TLE。
求教常数大的地方,谢谢。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<complex>
#include<cstdlib>
#include<climits>
#include<complex>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

#define cp complex<double>

inline const int Get_Int() {
int num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

const int maxn=524288+5;
const double pi=acos(-1);

struct FastFourierTransform {
int n;
cp omega[maxn],iomega[maxn];

void init(int n) {
this->n=n;
for(int i=0; i<n; i++) {
omega[i]=cp(cos(2*pi/n*i),sin(2*pi/n*i));
iomega[i]=conj(omega[i]);
}
}

void transform(cp* a,cp* omega) {
int k=log2(n);
for(int i=0; i<n; i++) {
int t=0;
for(int j=0; j<k; j++)if(i&(1<<j))t|=(1<<(k-j-1));
if(i<t)swap(a[i],a[t]);
}
for(int len=2; len<=n; len*=2) {
int mid=len>>1;
for(cp* p=a; p!=a+n; p+=len)
for(int i=0; i<mid; i++) {
cp t=omega[n/len*i]*p[mid+i];
p[mid+i]=p[i]-t;
p[i]+=t;
}
}
}

void dft(cp* a) {
transform(a,omega);
}

void idft(cp* a) {
transform(a,iomega);
for(int i=0; i<n; i++)a[i]/=n;
}
} fft;

char A[maxn],B[maxn];
int n,m,a[maxn],b[maxn];
cp ans[maxn];
vector<int>Ans;

int main() {
m=Get_Int();
n=Get_Int();
scanf("%s%s",A,B);
reverse(A,A+m);
for(int i=0; i<m; i++)if(A[i]!='*')a[i]=A[i]-'a'+1;
for(int i=0; i<n; i++)if(B[i]!='*')b[i]=B[i]-'a'+1;
//init
int N=1;
while(N<n+m)N<<=1;
fft.init(N);
static cp c1[maxn],c2[maxn];
//1
for(int i=0; i<N; i++) {
c1[i]=cp(a[i]*a[i]*a[i],0);
c2[i]=cp(b[i],0);
}
fft.dft(c1);
fft.dft(c2);
for(int i=0; i<N; i++)ans[i]=c1[i]*c2[i];
//2
for(int i=0; i<N; i++) {
c1[i]=cp(a[i]*a[i],0);
c2[i]=cp(b[i]*b[i],0);
}
fft.dft(c1);
fft.dft(c2);
for(int i=0; i<N; i++)ans[i]-=cp(2,0)*c1[i]*c2[i];
//3
for(int i=0; i<N; i++) {
c1[i]=cp(a[i],0);
c2[i]=cp(b[i]*b[i]*b[i],0);
}
fft.dft(c1);
fft.dft(c2);
for(int i=0; i<N; i++)ans[i]+=c1[i]*c2[i];
//cal
fft.idft(ans);
for(int i=m-1; i<n; i++)if(round(ans[i].real())==0)Ans.push_back(i-m+2);
printf("%d\n",Ans.size());
for(int x:Ans)printf("%d ",x);
return 0;
}
姥爷们赏瓶冰阔落吧~