Question meaning:
Give you a string r, find a string s, and make the prefix of s 1 + s 2 + s 3 +... + s n + s = r.
Solution:
KMP + greedy.
Initially, r [1] is assigned to s [1]. Each character in r matches s in sequence from front to back. When the matching fails, it indicates that this character does not appear in the pattern string. It is put to the end by greedy thinking (if the preceding requirements are met, the shortest must start with the last exact match ), therefore, all the characters from the last exact match to the character are used as the new pattern string to continue matching.
When the exact match is performed, the Location Value of the last exact match is updated.
Code:
<SPAN style = "FONT-SIZE: 18px ">#include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <set> # include <stack> # include <list> # include <queue> # define eps 1e-6 # define INF 0x1f1f1f1f # define PI acos (-1.0) # define ll _ int64 # define lson l, m, (rt <1) # define rson m + 1, r, (rt <1) | 1 using namespace std; # define M 100005 /* Freopen ("data. in "," r ", stdin); freopen (" data. out "," w ", stdout); */char rr [M], pp [M]; int rn, pn, next [M]; void getnext (int s) {int j = next [s-1]; // you only need to start from the previous one. // int j = s-1; for (int I = s; I <= pn; I ++) {while (j> 0 & pp [j + 1]-pp [I]) j = next [j]; if (pp [j + 1] = pp [I]) j ++; next [I] = j;} return ;} int main () {int ca = 0; while (scanf ("% s", rr + 1 )! = EOF) {rn = strlen (rr + 1); pp [1] = rr [1]; pn = 1; next [1] = 0; int last = 1; // record the position where int j = 0; for (int I = 1; I <= rn; I ++) {while (j> 0 & pp [j + 1]-rr [I]) j = next [j]; if (pp [j + 1] = rr [I]) j ++; if (j = pn) // found a new exact match {last = I-pn + 1; j = next [j]; // jump back to a} else if (j = 0) // new letters can only be used as the last {int tmp = pn; for (int k = last + pn; k <= I; k ++) pp [++ pn] = rr [k]; getnext (tmp + 1); // not getnext (last + tmp) last increases with I, wa a morning // j = pn;} printf ("Case % d: % d \ n", ++ ca, rn-last + 1);} return 0 ;} </SPAN>