散列+哈希

散列法:

#include <cstdio>
#include <iostream>
#include <string.h>
using namespace std;
const int N = 100010, null = 0x3f3f3f3f;
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 find1(int x) //开放寻址法
{
    int k = (x % N + N) % N;
    while(h[k] != null && h[k] != x)
    {
        k++;
        if(k == N) k = 0;
    }
    return k;
}
int main()
{
    int n;
    cin>>n;
    memset(h, -1, sizeof h);
    while(n--)
    {
        char op;
        int x;
        cin>>op>>x;
        if(op == 'I')
            insert(x);
        else{
            if(find(x)) puts("Yes");
            else puts("No");
        }
    }
}

 

 

字符串哈希:

#include <cstdio>
#include <iostream>
#include <string.h>
using namespace std;
typedef unsigned long long  ULL;
const int N = 100010, P = 131;
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];
}
int main()
{
    cin>>n>>m>>str+1;
    p[0] = 1;
    for(int i = 1;i<=n;i++)
    {
        p[i] = p[i-1] * P;
        h[i] = h[i-1] * P + str[i];
    }
    while(m--)
    {
        int l1,r1,l2,r2;
        cin>>l1>>r1>>l2>>r2;
        if(get(l1,r1) == get(l2,r2)) puts("Yes");
        else puts("No");
    }
}

 

posted @ 2020-04-13 23:49  龙雪可可  阅读(106)  评论(0编辑  收藏  举报
****************************************** 页脚Html代码 ******************************************