Ural 1684. Jack & #39; s last word KMP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.