哈希has散列-字符串hash

維護一個集合,支持如下幾種操作:

  1. “I x”,插入一個數x;
  2. “Q x”,詢問數x是否在集合中出現過;

現在要進行N次操作,對於每個詢問操作輸出對應的結果。

輸入格式

第一行包含整數N,表示操作數量。

接下來N行,每行包含一個操作指令,操作指令爲”I x”,”Q x”中的一種。

輸出格式

對於每個詢問指令“Q x”,輸出一個詢問結果,如果x在集合中出現過,則輸出“Yes”,否則輸出“No”。

每個結果佔一行。

數據範圍

1≤N≤1051≤N≤105
−109≤x≤109−109≤x≤109

輸入樣例:

5
I 1
I 2
I 3
Q 2
Q 5

輸出樣例:

Yes
No
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;

const int N=100003;
int n;
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++;
}


int  find(int x){
  int k=(x%N+N)%N;
  int t=h[k];
  while(t!=-1){
    if(e[t]==x)
      return 1;
    t=ne[t];
  }
  return 0;
}
int main(){
  scanf("%d",&n);
  memset(h,-1,sizeof(h));
  while(n--){
    char op[2];
    int x;
    scanf("%s%d",op,&x);
    if(op[0]=='I'){
        insert(x);
    }
    else{
        if(find(x))
            printf("Yes\n");
        else
            printf("No\n");
    }
  }
 return 0;
}

 

給定一個長度爲n的字符串,再給定m個詢問,每個詢問包含四個整數l1,r1,l2,r2l1,r1,l2,r2,請你判斷[l1,r1l1,r1]和[l2,r2l2,r2]這兩個區間所包含的字符串子串是否完全相同。

字符串中只包含大小寫英文字母和數字。

輸入格式

第一行包含整數n和m,表示字符串長度和詢問次數。

第二行包含一個長度爲n的字符串,字符串中只包含大小寫英文字母和數字。

接下來m行,每行包含四個整數l1,r1,l2,r2l1,r1,l2,r2,表示一次詢問所涉及的兩個區間。

注意,字符串的位置從1開始編號。

輸出格式

對於每個詢問輸出一個結果,如果兩個字符串子串完全相同則輸出“Yes”,否則輸出“No”。

每個結果佔一行。

數據範圍

1≤n,m≤1051≤n,m≤105

輸入樣例:

8 3
aabbaabb
1 3 5 7
1 3 6 8
1 2 1 2

輸出樣例:

Yes
No
Yes
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;

const int N=100010,P=1331;

typedef unsigned long long ULL;

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

int ha(int l,int r){
   return h[r]-h[l-1]*p[r-l+1];
}

int main(){
  p[0]=1;
  scanf("%d%d",&n,&m);
  scanf("%s",str+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 l,r,L,R;
    scanf("%d%d%d%d",&l,&r,&L,&R);
    if(ha(l,r)==ha(L,R))
        printf("Yes\n");
    else
        printf("No\n");
  }
 return 0;
 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章