字串HASH模板 取自挑戰程式設計競賽(第2版)

來源:互聯網
上載者:User

標籤:blog   for   2014   ar   log   設計   ef   file   

/*===================================================*    從b串中尋找和a串長度相同的子串,返回開始位置    不保證絕對正確,發生衝突機率為O(sqrt(n)),    n為雜湊函數的最大值\*===================================================*/#define ull unsigned long longconst ull B = 1e8+7;    /*according to the book*/const int MAXN = 1001;char a[MAXN],b[MAXN];int HashFind()/*返回匹配位置的開始處的下標,-1表示沒有匹配*/{    int al=strlen(a),bl=strlen(b);    if(al>bl)return -1;    ull t=1,ah=0,bh=0;    for(int i=0;i<al;i++)    {        t*=B;        ah=ah*B+a[i];        bh=bh*B+b[i];    }    for(int i=0;i+al<=bl;i++)    {        if(ah == bh)return i;        if(i+al < bl)bh=bh*B+b[i+al]-b[i]*t;    }    return -1;}/*===================================================*    滾動雜湊--滾動通過ull的溢出實現,相當於mod 2^64\*===================================================*/#define ull unsigned long longconst int MAXN = 1001;const ull B = 1e8+7;    /*according to the book*/char a[MAXN],b[MAXN];int OverLap()/*a的尾碼和b的首碼相等的最大長度*/{    int al=strlen(a),bl=strlen(b),ans=0;    int minlen=min(al,bl);    ull t=1,ah=0,bh=0;    for(int i=1;i<minlen;i++)    {        ah=ah+a[al-i]*t;        bh=bh*B+b[i-1];        if(ah == bh)ans=i;        t*=B;    }    return ans;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.