KMP hdu-2594 Simpsons 'den den Talents

Source: Internet
Author: User

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 ;}


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.