ハッシュ+ハッシュ

ハッシュ法:

#include <cstdio> 
#include <iostream> 
#include < string .h>
 using  namespace std;
const  int N = 100010null = 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;
    forint i = h [k]; i!=- 1 ; i = ne [i])
         if(e [i] == x)
             return  true ;
    falseを返し ます
} 
int find1(int x)// 开放寻址法
{
     int k =(x%N + N)%N;
    while(h [k]!= null && h [k]!= x)
    { 
        k ++ ;
        if(k == N)k = 0 ;
    }
    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(" はい" );
            else puts(" いいえ" ); 
        } 
    } 
}

 

 

文字列ハッシュ:

#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 getint l、int r)
{ 
    return h [r] -h [l- 1 ] * p [r-l + 1 ]; 
} 
int main()
{ 
    cin>> n >> m >> str + 1 ; 
    p [ 0 ] = 1 ;
    forint 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;
        ifget(l1、r1)== get(l2、r2))puts(" はい" );
        そうでなければ puts(" いいえ" ); 
    } 
}

 

おすすめ

転載: www.cnblogs.com/longxue1991/p/12695100.html