您的位置:首页 > 编程语言 > Go语言

String matching using Rabin-Karp Algorithm

2007-05-15 02:57 288 查看

Problem

Brian is an enthusiast of computer games, especially those that simulate virtual reality. Now he is in front of the Star Gate. In order to open the gate he must break the protection as quickly as he can. Breaking the protection means to match a given code (a sequence of numbers) against the gate protection (a very long sequence of numbers). The starting position of the first occurrence of the code within the sequence opens the gate. Can you help him?
The code is a sequence of at most 60000 integer numbers between 0 and 255. The gate protection contains integer numbers between 0 and 255. Your program must find the first match if there is one, or report the absence of a match.

Input

The text input file contains several data sets. Each data set has the following format:

l the length of the code

l the sequence of numbers representing the code

l the number of integers in the gate protection

l the sequence of numbers representing the gate protection

code_dimension

integer1 integer2 … integercode_dimension

protection_dimension

integer1 integer2 … integerprotection_dimension

White spaces may occur freely in the input.

Output

The results must be printed on the standard output. For each given data set, print the result on a separate line. The result is a number that represents the position (starting from zero) of the first occurrence of the code in the gate protection, or the message no solution if there is no match.

// (Introduction to algorithms 32.2 Rabin-Karp算法)


#include <iostream>


#include <stdio.h>


using namespace std;




void RABIN_KARP_MATCHER(unsigned char* T, int len_T, unsigned char* P, int len_P, int d, int q)




...{


int i;


int n=len_T;


int m=len_P;


int h=1;


for(i=1; i<=m-1; i++)




...{


h=(h*d)%q;


}


int p=0;


int t=0;


for(i=0; i<m; i++)




...{


p=(d*p+P[i])%q;


t=(d*t+T[i])%q;


}


int s;


for(s=0; s<n-m+1; s++)




...{


if(p==t)




...{


for(i=0; i<m; i++)




...{


if(P[i]!=T[s+i])


break;


}


if(i==m)




...{


cout<<s<<endl;


return;


}


}


if(s<n-m)


t=mod((d*(t-T[s]*h)+T[s+m]),q);


}


cout<<"no solution ";


return ;


}




int main()




...{


int code_len;


int protect;


int i;


while(scanf("%d", &code_len)!=EOF)




...{


unsigned char* code=new unsigned char[code_len];


for(i=0; i<code_len; i++)




...{


scanf("%hu", &code[i]);


}


scanf("%d", &protect);


unsigned char* pro=new unsigned char[protect];


for(i=0; i<protect; i++)




...{


scanf("%hu", &pro[i]);


}


RABIN_KARP_MATCHER(pro, protect, code , code_len, 128, 6999997); // d*q < 字长


}


return 0;


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: