KMP hdu-1686-Oulipo

Source: Internet
Author: User

Question link:

Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1686

Question meaning:

For two strings, calculate the number of repetitions of the first string in the second string, which can overlap.

Solution:

Directly use KMP. If a match is successful, set J to next [J.

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 maxn1 11000 # define maxn2 1100000 # define ll _ int64char save1 [maxn1], save2 [maxn2]; int next [maxn1], N1, N2; void getnext () {Int J = 0; next [1] = 0; For (INT I = 2; I <= N1; I ++) {While (j> 0 & save1 [J + 1]-save1 [I]) J = next [J]; if (save1 [J + 1] = save1 [I]) J ++; next [I] = J;} return; // note that the next array stores the maximum length of A1 ---- an-1} ll KMP () {Int J = 0; ll ans = 0; For (INT I = 1; I <= n2; I ++) {While (j> 0 & save1 [J + 1]-save2 [I]) J = next [J]; if (save1 [J + 1] = save2 [I]) J ++; If (j = N1) {ans ++; j = next [J]; // It can be repeated. If it cannot be repeated, set J to 0} return ans;} int main () {int t; scanf ("% d", & T ); while (t --) {scanf ("% S % s", save1 + 1, save2 + 1); save1 [0] = save2 [0] = 'K '; n1 = strlen (save1)-1, n2 = strlen (save2)-1; // printf ("% d \ n", N1, N2); getnext (); printf ("% i64d \ n", KMP ();} 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.