Poj(1220),hash

本文分享了解决POJ 1200问题的实战经验,通过使用Karp-Rabin算法将字符串转换为数字进行Hash处理,解决了无限内存限制、运行错误等问题。文章提供了完整的C++代码实现。

题目链接:http://poj.org/problem?id=1200

这个题,我真是无限MLE,RE,WA,太伤心了,还是写一下吧。题意很简单(英语很好读),最后看了一下金海峰的思路。果然,应该是我的这个hash表有点问题,最好是用正确的算法吧,不乱创造了。karp-rabin把字符串转化成数字的算法,一个字符串有n种字符构成,把每种字符对应为0~n-1中的一个数字,把字母换成对应的数字之后,对于固定长度的串,每个串都与一个唯一的n进制数对应。这样就可以hash了。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define maxn 16000005

bool hash[maxn];
int name[260];
int n, nc;
char st[maxn];

int main()
{
    //freopen("t.txt", "r", stdin);
    scanf("%d%d%s", &n, &nc, st);
    memset(name, 0, sizeof(name));
    memset(hash, 0, sizeof(hash));
    int len = strlen(st);
    int t =0;
    for (int i =0; i < len; i++)
        if (name[st[i]] ==0)
            name[st[i]] = t++;
    int temp =0;
    t = nc;
    for (int i =0; i < n -1; i++)
    {
        temp = temp * nc + name[st[i]];
        t *= nc;
    }
    int ans =0;
    for (int i = n -1; i < len; i++)
    {
        temp = (temp * nc + name[st[i]]) % t;
        if (!hash[temp])
        {
            ans++;
            hash[temp] =true;
        }
    }
    printf("%d\n", ans);
    return 0;
}

 

转载于:https://www.cnblogs.com/TreeDream/p/5858442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值