2018 ACM-ICPC 中國大學生程式設計競賽線上賽 H-Rock Paper Scissors Lizard Spock.
阿新 • • 發佈:2019-02-02
分析:石頭剪刀布加強版。
把短的字串跟長的字串從某一位置進行匹配,問最多可以匹配多少位。
把其中一個串反轉,對每一種字元單獨計算。
字元匹配的過程看做卷積和,則當前要匹配的字元對應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; }