Question link:
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 2594
Question meaning:
For two strings, find that the prefix of the first string is the maximum length of the suffix of the second string.
Solution:
First obtain the next array of the first string, and then match the second string.
Note that when the second string is the prefix of the first string, the next array cannot include itself. Process it separately.
Code:
# Include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <stack> # include <list> # include <queue> # define EPS 1e-6 # define Inf (1 <30) # define PI ACOs (-1.0) using namespace STD; # define maxn 55000 char save1 [maxn], save2 [maxn]; int next [maxn], N1, N2; void getnext1 () {Int J = 0; next [1] = 0; For (INT I = 2; I <= N1; I ++) {whil E (j> 0 & save1 [J + 1]! = Save1 [I]) J = next [J]; If (save1 [J + 1] = save1 [I]) J ++; next [I] = J ;}} int getnext2 () {Int J = 0; next [1] = 0; For (INT I = 2; I <= n2; I ++) {While (j> 0 & save1 [J + 1]! = Save2 [I]) J = next [J]; If (save1 [J + 1] = save2 [I]) J ++; if (I = n2) // return the last one directly. Return J; // next [I] = J; // next cannot be obtained in the second string // printf ("% d \ n", I, next [I]) ;}} int main () {While (scanf ("% S % s", save1 + 1, save2 + 1 )! = EOF) {save1 [0] = save2 [0] = 'K'; n1 = strlen (save1)-1, n2 = strlen (save2)-1; if (N2 <= N1) // when the second string is a substring of the first string, it is processed separately {'if (strncmp (save1 + 1, save2 + 1, N2) = 0) {printf ("% S % d \ n", save2 + 1, N2); Continue ;}} getnext1 (); int ans = getnext2 (); if (ANS) {save1 [ans + 1] = '\ 0'; printf ("% S % d \ n", save1 + 1, ANS );} else puts ("0");} return 0 ;}