Poj 2752 seek the name (KMP)

Source: Internet
Author: User
Http://poj.org/problem? Id = 2752

The next Array application of KMP. In a word, next [J] must be the maximum value that satisfies STR [1 .. next [J] = STR [J-next [J] + 1. J.

 

Take abababa as an example. If next [7] = 5, STR [1 .. 5] = STR [3 .. 7], apparently STR [3 .. 5] = STR [5 .. 7].

Next [5] = 3, STR [1 .. 3] = STR [3 .. 5], according to the above results, we can see STR [1 .. 3] = STR [5 .. 7].

Because of the nature of the next array, it is clear that the above is true for any situation, and the value saved by each next can make STR [1 .. next [J] = STR [Len-next [J] + 1 .. len].

Here we only need to find the non-zero value of next from Len to 1, and then output it in reverse order.

Code:

# Include <cstdio>
# Include <cstring>
Char STR [400001];
Int next [400001];
Int ans [400001];
Int Len;
Void get_next () {// based on known next
Next [1] = 0;
Int J = 0;
For (INT I = 2; I <= Len; I ++ ){
While (j> 0 & STR [J + 1]! = STR [I])
J = next [J];
If (STR [J + 1] = STR [I]) J ++;
Next [I] = J;
}
}
Int main (){
Int I, J;
While (~ Scanf ("% s", STR + 1 )){
Len = strlen (STR + 1 );
Get_next ();
Ans [0] = I = Len;
J = 1;
While (next [I]> 0 ){
Ans [J ++] = next [I];
I = next [I];
}
For (I = J-1; I> = 0; I --)
Printf ("% d", ANS [I]);
Printf ("\ n ");
}
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.