zoukankan      html  css  js  c++  java
  • 字符串哈希

    #include<bits/stdc++.h>
    using namespace std;
    #define far(i,t,n) for(int i=t;i<n;++i)
    typedef long long ll;
    typedef unsigned long long ull;
     
    char t[1000010];
    char w[10010];
    const int p=12582917;
    ull po[10010];
    ull Hash[1000010];
     
    void initPo()//预处理p^(r-l+1)
    {
        po[0]=1;
        po[1]=p;
        far(i,2,10002)
            po[i]=po[i-1]*p;
    }
     
    ull getSingleHash(char c[],int n)
    {
        Hash[0]=c[0]-'A';
        far(i,1,n)
        {
            Hash[i]=Hash[i-1]*p;
            Hash[i]+=c[i]-'A';
        }
    }
     
    ull getHash(int l,int r)
    {
        if(l==0)
            return Hash[r];
        return Hash[r]-Hash[l-1]*po[r-l+1];
    }
     
    int main()
    {
        int Kase;
        cin>>Kase;
        initPo();
        while(Kase--)
        {
            scanf("%s%s",w,t);
            int lw=strlen(w),lt=strlen(t);
            ull x=w[0]-'A';
            far(i,1,lw)
                x=x*p+(w[i]-'A');
            getSingleHash(t,lt);
            int ans=0;
            for(int i=0;i<=lt-lw;++i)
            {
               // cout<<i<<" "<<getHash(i,i+lw)<<endl;
                if(x==getHash(i,i+lw-1))
                    ++ans;
            }
     
            printf("%d
    ",ans);
        }
     
        return 0;
    }
  • 相关阅读:
    稠密光流
    分水岭分割
    Haar小波分析
    内积空间
    矩阵LU分解
    opencv笔记---contours
    Deformable Templates For Eye Detection
    最小二乘法
    字符集及编码
    层次聚类
  • 原文地址:https://www.cnblogs.com/acmLLF/p/14603025.html
Copyright © 2011-2022 走看看