[字符串哈希] lg-P3370. 【模板】字符串哈希(字符串哈希+手写哈希表+模板题)

1. 题目来源

链接:P3370 【模板】字符串哈希

相关题目:[字符串哈希+模板]字符串哈希

2. 题目解析

字符串哈希模板题,在此是直接哈希整个字符串,并加以存储。利用 vector 模拟开散列,是手写哈希表。

对于相同哈希值的字符串加以存储,再进行相等判断,不相等则说明两字符串不等,则答案 ++ 即可。

而在 [字符串哈希+模板]字符串哈希 中则更加高明,可以对于任意一个前缀进行字符串哈希来进行任意子串的判等,属于字符串哈希的进阶用法。

代码:

// https://www.luogu.com.cn/problem/P3370

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

const int N = 1505, BASE = 261, MOD = 23333;

int n, ans;
char a[N];
vector<string> h[MOD+5];

void insert() {
    int hash = 1;
    for (int i = 0; a[i]; i ++ ) hash = (hash * 1ll *  BASE + a[i]) % MOD;
    string t = a;
    for (int i = 0; i < h[hash].size(); i ++ ) 
        if (t == h[hash][i])
            return ;
    h[hash].push_back(t);
    ans ++ ;
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i ++ ) {
        scanf("%s", a);
        insert();
    }
    printf("%d\n", ans);
    return 0;    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值