传送门:Rock Paper Scissors Lizard Spock.
这题还有一个弱化版:GYM 101667-H
分析:石头剪刀布加强版。
把短的字符串跟长的字符串从某一位置进行匹配,问最多可以匹配多少位。
把其中一个串反转,对每一种字符单独计算。
字符匹配的过程看做卷积和,则当前要匹配的字符对应1,否则为0。
用FFT快速求解,最后取最大值。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
const int maxn = 4e6+10;
const double PI = acos(-1.0);
struct complex{
double r,i;
complex (double r=0.0, double i=0.0):r(r),i(i){}
complex operator +(const complex &rhs) {return complex(r+rhs.r,i+rhs.i); }
complex operator -(const complex &rhs) {return complex(r-rhs.r,i-rhs.i); }
complex operator *(const complex &rhs) {return complex(r*rhs.r-i*rhs.i,r*rhs.i+i*rhs.r); }
};
void change(complex y[], int len) {
int i,j,k;
for (int i=1, j = len/2; i<len-1; i++) {
if (i<j) swap(y[i],y[j]);
k = len/2;
while (j>=k) {
j-=k;
k/=2;
}
if (j<k) j+=k;
}
}
void fft(complex y[], int len, int on) {
change(y,len);
for (int h=2; h<=len; h<<=1) {
complex wn(cos(-on*2*PI/h),sin(-on*2*PI/h));
for (int j=0; j<len; j+=h) {
complex w(1,0);
for (int k=j; k<j+h/2; k++) {
complex u = y[k];
complex t = w*y[k+h/2];
y[k] = u+t;
y[k+h/2] = u-t;
w = w*wn;
}
}
}
if (on == -1) {
for (int i=0; i<len; i++) y[i].r /= len;
}
}
complex x1[maxn],x2[maxn];
char a[maxn/2],b[maxn/2],a1[maxn/2];
int sum[maxn],ans[maxn];
int n1,n2;
void calc(char c){
int len = 1;
while (len<n1*2 || len<n2*2) len<<=1;
for (int i=0; i<n1; i++) x1[i] = complex(a[i]==c,0);
for (int i=n1; i<len; i++) x1[i] = complex(0,0);
for (int i=0; i<n2; i++) x2[i] = complex(b[i]==c,0);
for (int i=n2; i<len; i++) x2[i] = complex(0,0);
fft(x1,len,1);
fft(x2,len,1);
for (int i=0; i<len; i++) x1[i] = x1[i]*x2[i];
fft(x1,len,-1);
for (int i=0; i<len; i++) sum[i] = (int)(x1[i].r+0.5);
len = n1+n2-1;
for (int i=0; i<len; i++) ans[i] += sum[i];
}
int main(){
while (scanf("%s%s",a1,b)==2) {
n1 = strlen(a1);
n2 = strlen(b);
for (int i=0; i<=n1+n2-1; i++) ans[i] = 0;
reverse(b,b+n2);
for (int i=0; i<n1; i++) {
if (a1[i] == 'P') a[i] = 'S';
else if (a1[i] == 'R') a[i] = 'P';
else if (a1[i] == 'L') a[i] = 'R';
else if (a1[i] == 'S') a[i] = 'K';
else if (a1[i] == 'K') a[i] = 'L';
}
calc('S'); calc('R'); calc('P'); calc('L'); calc('K');
for (int i=0; i<n1; i++) {
if (a1[i] == 'P') a[i] = 'L';
else if (a1[i] == 'R') a[i] = 'K';
else if (a1[i] == 'L') a[i] = 'S';
else if (a1[i] == 'S') a[i] = 'R';
else if (a1[i] == 'K') a[i] = 'P';
}
calc('S'); calc('R'); calc('P'); calc('L'); calc('K');
int total = 0;
for (int i=n2-1; i<n1+n2-1; i++) total = max(ans[i],total);
printf("%d\n",total);
}
return 0;
}
本文介绍了一种使用快速傅里叶变换(FFT)解决字符串匹配问题的方法,通过将字符串转换为数值序列并利用FFT进行高效卷积计算,实现了字符串的匹配与计数。
814

被折叠的 条评论
为什么被折叠?



