RABIN_KARP_MATCHER1多模式串(等长)匹配

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int d=26,p=100007;
struct data{ char ch[1002];};
data ch1,ch2[1002];
int l1,l2,h,s[1002],ans[1002][1002],n;
void init(){
scanf("%d\n%s\n",&n,&ch1.ch);
for (int i=1;i<=n;i++) scanf("%s\n",&ch2[i].ch);
l1=strlen(ch1.ch); l2=strlen(ch2[1].ch); h=1;
memset(s,0,sizeof(s));
memset(ans,0,sizeof(ans));
}


bool check(int x,int y){
for (int k=0;k<l2;k++)
 if (ch2[y].ch[k]!=ch1.ch[k+x]) return 0;
return 1;
}


void RABIN_KARP_MATCHER(){
for (int i=1;i<l2;i++) h=(h*d)%p;
for (int i=0;i<l2;i++){
s[0]=(d*s[0]+ch1.ch[i]-96)%p;
for (int j=1;j<=n;j++) s[j]=(d*s[j]+ch2[j].ch[i]-96)%p;}
for (int i=0;i<=l1-l2;i++){
for (int j=1;j<=n;j++)
 if (s[j]==s[0]&&check(i,j)) ans[j][++ans[j][0]]=i+1;
if (i<l1-l2) s[0]=((d*(s[0]-h*(ch1.ch[i]-96))+ch1.ch[i+l2]-96)%p+p)%p;
}
}


void print(){
for (int i=1;i<=n;i++)
{  for (int j=1;j<=ans[i][0];j++) printf("%d ",ans[i][j]);
  printf("\n");
}
}


int main(){
init();
RABIN_KARP_MATCHER();
print();
return 0;
}

你可能感兴趣的:(RABIN_KARP_MATCHER1多模式串(等长)匹配)