HDU 4821 (hash)

这道题最重要的不仅是hash这种算法,更要学会利用好STL中的<map>才行。

将连续的L个字符经过hash赋值,最后线性判断。其中的判断步骤用到了map的插入特性。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
#define maxn 500010
#define ull unsigned long long

ull sum[maxn];
map<ull, bool> mp;
ull l, m;

int solve(ull be, ull len)
{
    int ret = 0;
    mp.clear();
    for(ull i = be; i < len; i += l)
    {
        if(mp[sum[i]])
        {
            while(sum[be] != sum[i])
            {
                mp[sum[be]] = 0;
                be += l;
            }
            mp[sum[be]] = 0;
            be += l;
        }
        mp[sum[i]] = 1;
        if((i - be) / l == m - 1)
        {
            ret++;
            mp[sum[be]] = 0;
            be += l;
        }
    }
    return ret;
}

int main()
{
    char c[maxn];
    while(~scanf("%d%d", &m, &l))
    {
        scanf("%s", c);
        ull len = strlen(c);
        ull base = 31;
        ull bit = 1;
        ull tmp = 0;
        for(ull i = 0; i < l; i++)
        {
            tmp = tmp * base + c[i] - 'a';
            bit *= base;
        }
        int ans = 0;
        sum[l - 1] = tmp;
        for(ull i = l; i < len; i++)
        {
            sum[i] = sum[i - 1] * base + c[i] - 'a'  - bit * (c[i - l] - 'a');
        }
        for(ull i = l - 1; i < l * 2 - 1; i++)
        {
            ans += solve(i, len);
        }
        printf("%d\n", ans);

    }
}
View Code

 

posted @ 2014-07-18 18:20  ouc_ye  阅读(315)  评论(0编辑  收藏  举报