Source: Ural 1684. Jack's last word
Enter a B and divide B into several segments. Each segment is the prefix of.
Train of Thought: B is the main string, and then use a to match B to record the maximum length of the I position of B, and then start from the back when cutting.
Suppose a = abac B = Abab, then assume that we have covered ABA before and after, and then B cannot cover AB from the back to the back. First, we can cover AB next time or AB.
Because the maximum length of the matching to the I position has been recorded, the length is used to go backwards from the end.
Assume that the maximum matched prefix of a recursive record is X, this time it should be regressed to I-X.
Assume that X is not regressed and Y is less than X, and X is regressing. The rest is that y-X will inevitably be regressing. Then, we can solve it once.
#include <cstdio>#include <cstring>const int maxn = 100010;char a[maxn], b[maxn];int f[maxn];int dp[maxn];char c[maxn*2];void get_fail(char* s){f[0] = f[1] = 0;int n = strlen(s);for(int i = 1; i < n; i++){int j = f[i];while(j && s[i] != s[j])j = f[j];if(s[i] == s[j])f[i+1] = j+1;elsef[i+1] = 0;}}int main(){while(scanf("%s %s", a, b) != EOF){get_fail(a);int n = strlen(b), m = strlen(a);int j = 0;for(int i = 0; i < n; i++){while(j && b[i] != a[j])j = f[j];if(a[j] == b[i])j++;dp[i] = j;if(j == m)j = f[j];}c[n*2] = 0;int len = n*2, i;for(i = n-1; i >= 0; ){int k = dp[i];if(k == 0)break;for(int j = i; j > i-k; j--)c[--len] = a[j-i+k-1];c[--len] = ' ';i = i-k;}if(i != -1)puts("Yes");else{puts("No");puts(c+len+1);}}return 0;}
Ural 1684. Jack & #39; s last word KMP