hdu4821 字串 hash (bkdrhash)

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   strong   for   2014   

題意: 給一個字串,和m,l, 找出這樣的子串: 長度為m*l, 由m個長度為l的串組成,每個串都不同。(s,size()<10^5)

字串hash典例。 這裡用的是bkdrhash 法。也是最常用的衝突最少的一種。原理:把字串和數值對應。這裡用base=31(一般用質數),

先是掃一遍,處理處每個位子到結尾構成的串的hash值(倒過來的),然後長度為l的子串的haash值就好算了。

之後枚舉開頭l個,每次向後翻滾,複雜度max(L*M, L*(S.SIZE/M))可以過,這裡用了map判重下。若枚舉開頭掃一遍,姿勢不優越過不了,極限可能:m=50000,l=1,複雜度(s,size*m)會逾時。 

關鍵一:那裡求hash值的時候+1,否則100,10這種hash值一樣。

開始擔心這樣減hash值會因為爆出現負值。其實不然:其一,  unsigned long long ,自動模數(最近在學彙編,的確如此啊),                                                                                     

其二:因為每次從後面向前推導:hash[i] = hash[i+1]*base+s[i]-‘a‘+1; ,本質自動模數,所以:hash[i]=s[i]-‘a‘+1+hash[i+l]*nbase[l] (每步自動模數),由於 s[i]-‘a‘+1  非負,所以有   

hash[i]》hash[i+l]*nbase[l]                  

(ps:感謝puyijie學長的指導)

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>#include<string>typedef unsigned long long ull;using namespace std;const int maxn= 100050;const ull base =31;ull nbase[maxn],hash[maxn];int m,l;map<ull, int> mp;int main(){ull tmp;nbase[0] = 1;for (int i = 1;i<maxn; i++){    nbase[i]=nbase[i-1]*base;}while (~scanf("%d%d",&m,&l)) {     string s;cin>>s;int slen=s.size();hash[slen] = 0;for (int i = slen-1; i >= 0; i--)hash[i] = hash[i+1]*base+s[i]-'a'+1;           //關鍵1int ans = 0;for (int i = 0; i<l&&i+m*l<=slen; i++){mp.clear();for (int j = i; j<i+m*l; j += l){tmp = hash[j] - hash[j+l]*nbase[l];mp[tmp]++;}if (mp.size() ==m)ans++;for (int j=i+m*l; j+l<=slen; j +=l) {tmp = hash[j-m*l] - hash[j-(m-1)*l]*nbase[l];mp[tmp]--;if (mp[tmp] == 0)                                mp.erase(tmp);tmp = hash[j] - hash[j+l]*nbase[l];mp[tmp]++;if (mp.size() == m)ans++;}}printf("%d\n", ans);}return 0;}







hdu4821 字串 hash (bkdrhash)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.