Definition of KMP algorithm and KMP exercise HDU 1711 number sequence (My template code)

Source: Internet
Author: User

You need to find the first matching position of array B in array A. If not, output-1.

Idea: Direct KMP algorithm (algorithm specific idea this ox write good http://blog.csdn.net/v_july_v/article/details/7041827)

AC code:

# Include <cstdio> # include <cstring> # include <stdlib. h >#include <iostream> using namespace STD; # define maxn 1000005int B [10005]; int A [maxn]; int next [maxn]; int n, m; /* void getnext () {next [0] =-1; int K =-1; Int J = 0; while (j <m) {If (k =-1 | B [J] = B [k]) {++ K; ++ J; next [J] = K ;} else {k = next [k] ;}}*/void getnext () {next [0] =-1; int K =-1; Int J = 0; while (j <m) {If (k =-1 | B [J] = B [k]) {++ J; ++ K; if (B [J]! = B [k]) next [J] = K; else next [J] = next [k];} else {k = next [k] ;}} int kmpsearch () {int I = 0, j = 0; while (I <n & J <m) {If (j =-1 | A [I] = B [J]) {I ++; j ++;} else J = next [J];} if (j = m) return I-j + 1; else return-1;} int main () {int I, j, T; scanf ("% d ", & T); While (t --) {scanf ("% d", & N, & M); for (I = 0; I <n; I ++) scanf ("% d", & A [I]); for (I = 0; I <m; I ++) scanf ("% d ", & B [I]); getnext (); printf ("% d \ n", kmpsearch ();} 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.