Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program karp;
- const TRUE_MOD = high(qword);
- var i:qword;
- str,substr:shortstring;
- mas:array of char;
- function gethash(new,old:char; prev:qword):qword;
- begin
- if prev + ord(new) - ord(old) >= 0 then
- result := (prev + ord(new) - ord(old)) mod TRUE_MOD
- else
- result := ((TRUE_MOD + prev + ord(new)) - ord(old)) mod TRUE_MOD;
- end;
- function compare(point:dword):boolean;
- var i:qword;
- begin
- for i := 1 to length(substr) do
- begin
- if substr[i] <> mas[point] then
- exit(false);
- point := (point + 1) mod length(substr);
- end;
- exit(true);
- end;
- function RabinCarp(str,substr:ShortString):boolean;
- var hash,subhash:qword;
- lastdigit:dword;
- begin
- hash := 0;
- subhash := 0;
- lastdigit := 0;
- if length(str) >= length(substr) then
- begin
- setLength(mas,length(substr));
- for i := 0 to length(mas) - 1 do
- mas[i] := str[i + 1];
- for i := 1 to length(substr) do
- subhash := (subhash + ord(substr[i])) mod TRUE_MOD;
- for i := 1 to length(substr) do
- hash := (hash + ord(str[i])) mod TRUE_MOD;
- if hash = subhash then
- if compare(lastdigit) then
- exit(true);
- i := length(substr) + 1;
- while (length(str) - length(substr) + 1 >0) do
- begin
- for i := i to length(str) do
- begin
- lastdigit:= lastdigit mod length(substr);
- hash := gethash(str[i],mas[lastdigit],hash);
- mas[lastdigit] := str[i];
- if hash = subhash then
- if compare((lastdigit + 1)mod length(substr)) then
- exit(true);
- lastdigit += 1;
- end;
- i := 1;
- read(str);
- end;
- exit(false);
- end;
- end;
- begin
- AssignFile(input,'input.txt');
- AssignFile(output,'output.txt');
- Reset(input);
- Rewrite(output);
- readln(substr);
- read(str);
- if RabinCarp(str,substr) then
- writeln(1)
- else
- writeln(0);
- close(input);
- close(output);
- end.
Add Comment
Please, Sign In to add comment