ArinaRaguzina

Untitled

Jan 24th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.14 KB | None | 0 0
  1. program karp;
  2.  
  3.  
  4. const TRUE_MOD = high(qword);
  5.  
  6. var i:qword;
  7.     str,substr:shortstring;
  8.     mas:array of char;
  9.  
  10.  
  11. function gethash(new,old:char; prev:qword):qword;
  12. begin
  13.     if prev + ord(new) - ord(old) >= 0 then
  14.         result := (prev + ord(new) - ord(old)) mod TRUE_MOD
  15.     else
  16.         result := ((TRUE_MOD + prev + ord(new)) - ord(old)) mod TRUE_MOD;
  17. end;
  18.  
  19. function compare(point:dword):boolean;
  20. var i:qword;
  21. begin
  22.     for i := 1 to length(substr) do
  23.     begin
  24.         if substr[i] <> mas[point] then
  25.             exit(false);
  26.         point := (point + 1) mod length(substr);
  27.     end;
  28.     exit(true);
  29. end;
  30.  
  31. function RabinCarp(str,substr:ShortString):boolean;
  32. var hash,subhash:qword;
  33.     lastdigit:dword;
  34. begin
  35.     hash := 0;
  36.     subhash := 0;
  37.     lastdigit := 0;
  38.     if length(str) >= length(substr) then
  39.     begin
  40.         setLength(mas,length(substr));
  41.         for i := 0 to length(mas) - 1 do
  42.             mas[i] := str[i + 1];
  43.         for i := 1 to length(substr) do
  44.             subhash := (subhash + ord(substr[i])) mod TRUE_MOD;
  45.         for i := 1 to length(substr) do
  46.             hash := (hash + ord(str[i])) mod TRUE_MOD;
  47.         if hash = subhash then
  48.            if compare(lastdigit) then
  49.               exit(true);
  50.         i := length(substr) + 1;
  51.         while (length(str) - length(substr) + 1 >0) do
  52.         begin
  53.             for i := i to length(str) do
  54.             begin
  55.                 lastdigit:= lastdigit mod length(substr);
  56.                 hash := gethash(str[i],mas[lastdigit],hash);
  57.                 mas[lastdigit] := str[i];
  58.                 if hash = subhash then
  59.                     if compare((lastdigit + 1)mod length(substr)) then
  60.                         exit(true);
  61.                 lastdigit += 1;
  62.             end;
  63.             i := 1;
  64.             read(str);
  65.         end;
  66.         exit(false);
  67.     end;
  68. end;
  69.  
  70. begin
  71.     AssignFile(input,'input.txt');
  72.     AssignFile(output,'output.txt');
  73.     Reset(input);
  74.     Rewrite(output);
  75.     readln(substr);
  76.     read(str);
  77.     if RabinCarp(str,substr) then
  78.        writeln(1)
  79.     else
  80.        writeln(0);
  81.     close(input);
  82.     close(output);
  83. end.
Add Comment
Please, Sign In to add comment