hdu 4821 字串hash+map判重 String (長春市賽區I題)

來源:互聯網
上載者:User

標籤:style   http   os   io   for   ar   div   line   

http://acm.hdu.edu.cn/showproblem.php?pid=4821

昨晚卡了很久,開始TLE,然後最佳化了之後,因為幾個地方變數寫混,一直狂WA,搞得我昨晚都失眠了,,,

這幾次hash軍寫錯的變數--tmp=(j==m-1)?ah[j]:(ah[j]-ah[j-m]*base[m]);  外層迴圈變數是i,我寫的字串hash的幾題都寫成tmp=(i==0)?ah[j]:(ah[j]-ah[j-m]*base[m]); 二逼啊

題目大意:

給定一個字串(最長10^5)。從中選一個長度為 m * l 的子串,要求該子串能拆分為m個長度為 l 的一一不同的串(串只要有一個字母不同即認為是不同)。問有多少種取法。


最佳化的方法--從字串第一個位置開始,每L個的hash都算出來,當到了第一個第m個L位置的時候,繼續往後算--去掉第一個L的hash值,加上第m*l+m的hash值

#include <cstdio>#include <cstring>#include <algorithm>#include <string>#include <iostream>#include <cmath>#include <map>#include <set>#include <queue>using namespace std;#define ls(rt) rt*2#define rs(rt) rt*2+1#define ull unsigned long long#define rep(i,s,e) for(int i=s;i<e;i++)#define repe(i,s,e) for(int i=s;i<=e;i++)#define CL(a,b) memset(a,b,sizeof(a))#define IN(s) freopen(s,"r",stdin)#define OUT(s) freopen(s,"w",stdin)const ull B = 1e8+7;const int MAXN = 100010;ull ah[MAXN],base[MAXN];char a[MAXN];int n;//length of aint main(){   //IN("hdu4821.txt");    int m,ll;    int ans=0,cnt,last,sc;    base[0]=1;    ull tmp;    rep(i,1,MAXN)        base[i]=base[i-1]*B;    while(~scanf("%d%d",&ll,&m))    {        scanf("%s",a);        n=strlen(a);        ah[0]=a[0];ans=0;        for(int i=1;i<=n;i++)            ah[i]=ah[i-1]*B+a[i]; //ah[i] 以i結尾的字串的hash值        for(int i=0;i<m && i+ll*m<=n;i++)        {            map<ull,int>mp;            for(int j=i+m-1;j<i+ll*m;j+=m)            {                tmp=(j==m-1)?ah[j]:(ah[j]-ah[j-m]*base[m]);                mp[tmp]++;            }            if(mp.size()==ll)ans++;            int pos=i+m-1;            tmp=(i==0)?ah[m-1]:(ah[pos]-ah[pos-m]*base[m]);            mp[tmp]--;            if(mp[tmp] == 0)mp.erase(tmp);            for(int j=i+ll*m+m-1;j<n;j+=m)            {                tmp=ah[j]-ah[j-m]*base[m];                mp[tmp]++;                if(mp.size()==ll)ans++;                pos+=m;                tmp=ah[pos]-ah[pos-m]*base[m];                mp[tmp]--;                if(mp[tmp] == 0)mp.erase(tmp);            }            mp.clear();        }        printf("%d\n",ans);    }    return 0;}


聯繫我們

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