思考:簡單不模式匹配,稍加思考就可以做的題目。
#include#include #include #include using namespace std; const int maxn = 50010; char a[maxn+5]; char b[maxn+5]; char t[maxn+5]; char p[maxn+5]; int f[maxn+5]; char res[maxn+5]; //Accepted 2594 0MS 632K 1263 B C++ Achiberx void getFail() { int len = strlen(p); f[0] = 0, f[1] = 0; int j = 0; for(int i = 1; i < len; i++) { j = f[i]; if(j && p[j]!=p[i]) j = f[j]; f[i+1] = p[j]==p[i] ? j+1 : 0; } } void match() { getFail(); int len = strlen(t); int j = 0; for(int i = 0; i < len; i++) { while(j && t[i]!=p[j]) j = f[j]; if(t[i]==p[j]) j++; } int idx = 0; for(int i = j-1; i >= 0; i--) { res[idx++] = p[i]; } res[idx] = '\0'; if(j==0) printf("0\n"); else printf("%s %d\n", res, j); } int main() { while(gets(a) && a[0]) { gets(b); int lena = strlen(a); int idx = 0; for(int i = lena-1; i >= 0; i--) { t[idx++] = a[i]; } t[idx] = '\0'; idx = 0; int lenb = strlen(b); for(int i = lenb-1; i >= 0; i--) { p[idx++] = b[i]; } p[idx] = '\0'; match(); } return 0; }