← 所有文章
算法

哈希表

/ 更新于 2026.06.07

算法-23

https://www.acwing.com/activity/content/problem/content/890/

拉链法

#include <cstring>
#include <iostream>

using namespace std;

const int N = 100003;

int h[N], e[N], ne[N], idx;

void insert(int x)
{
    int k = (x % N + N) % N;//负数取模固定套路
    e[idx] = x;
    ne[idx] = h[k];
    h[k] = idx ++ ;//头插入
}

bool find(int x)
{
    int k = (x % N + N) % N;
    for (int i = h[k]; i != -1; i = ne[i])
        if (e[i] == x)
            return true;

    return false;
}

int main()
{
    int n;
    scanf("%d", &n);

    memset(h, -1, sizeof h);//初始化槽位

    while (n -- )
    {
        char op[2];
        int x;
        scanf("%s%d", op, &x);//细节:使用scanf输入字符串可以过滤空格占位符影响

        if (*op == 'I') insert(x);//*op相当于取op首地址即为目标字符
        else
        {
            if (find(x)) puts("Yes");
            else puts("No");
        }
    }

    return 0;
}

字符串hash

算法-25

IMG_2446A47CCE60-1

#include <iostream>
#include <algorithm>

using namespace std;

typedef unsigned long long ULL;

const int N = 100010, P = 131;//经验值P

int n, m;
char str[N];
ULL h[N], p[N];

ULL get(int l, int r)
{
    return h[r] - h[l - 1] * p[r - l + 1];//字符串hash公式
}

int main()
{
    scanf("%d%d", &n, &m);
    scanf("%s", str + 1);

    p[0] = 1;
    for (int i = 1; i <= n; i ++ )//注意从1开始防止越界引发分类讨论
    {
        h[i] = h[i - 1] * P + str[i];//预处理前缀hash
        p[i] = p[i - 1] * P;//预处理P次幂
    }

    while (m -- )
    {
        int l1, r1, l2, r2;
        scanf("%d%d%d%d", &l1, &r1, &l2, &r2);

        if (get(l1, r1) == get(l2, r2)) puts("Yes");
        else puts("No");
    }

    return 0;
}
— 感谢读到这里 — 回到首页 ↗