"String Hash" "Bkdrhash" "Rabin-karp algorithm" template

Source: Internet
Author: User

#include <cstdio> #include <iostream> #include <cstring> #include <string> #include <set> using namespace std; #define MAXN 100001typedef unsigned long long ull;const ull seed=31;ull Seeds[maxn];char s[maxn],s2[ma Xn];int poss[maxn];//Violent string comparison bool Strcmp (const char a[],const int &l1,const int &r1,const char b[],const int &l 2,const int &r2) {for (int i=l1,j=l2;i<r1;++i,++j) if (A[i]!=b[j]) return 0;return 1;}  Natural overflow, L first pointer, R tail pointer, left closed right open ull bkdrhash (const char str[],const int &l,const int &r) {ull res=0;for (int i=l;i<r;++i) Res=res*seed+str[i];return Res;} Preprocessing to facilitate the transfer of hash (S[i...i+m-1] and hash (s[i+1...i+m]) void Init_seeds () {seeds[0]=1;for (int i=1;i<maxn;++i) seeds[i] =seeds[i-1]*seed;} Text string lookup, s text string, sub substring int rabinkarp (const char s[],const char sub[]) {int N=strlen (s), M=strlen (sub), Ull hsub=bkdrhash (Sub,    0,M), Hs=bkdrhash (S,0,m), for (int i=0;i<=n-m;++i) {if (hs==hsub && Strcmp (s,i,i+m,sub,0,m)) return i; Hs= (Hs-s[i]*seeds[m-1]) *seed+S[I+M];//O (1) transfer}return-1;}  int main () {init_seeds (); while (1) {scanf ("%s%s", S,S2);  printf ("%d\n", Rabinkarp (S,S2)); }return 0;}

String hash, Bkdrhash, Rabin-karp algorithm template

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.