Rabin-karp ACM Training

Source: Internet
Author: User

Solving problems

Find the position or number of T occurrences in S. Suppose the length of S is N, T is M, and the hash value of the string that enumerates s length m is compared to the hash value of T. The optimization using a scrolling hash at this point does not have the complexity of O (MN).

Algorithm description Scrolling Hash

Take two appropriate primes B and H, assuming the string c = c1c2c3c4, define the hash function:

H (C) = (c1bm-1 + c2bm-2 + c3bm-3 + ... + cmb0) mod h

where B is the cardinality, which is equivalent to the string as a B-binary. When calculating the M-long string in S, the hash value of the string after each backward slide of one character and the Hahs value of the previous string have the following relationship:

H (s[k+1. k+m]) = h (s[k). K+M-1] * B-SKBM + sk+m) mod h

This computes the hash value to calculate the hash value of all positions in s in the time of O (n), thus completing the string match in the time of O (M + N).

Hit: The actual use of the H is 264, using a long long int natural overflow eliminates the time to take the modulus.

PS: The original r-k algorithm also needs to check for hash value collisions, but this will degrade the algorithm complexity to O (MN), and the race is only relatively non-checked.

Template
1 Long Long int ull;

Rabin-karp ACM Training

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.