Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <string>
  4. #include <math.h>
  5. #include <fstream>
  6.  
  7.  
  8. using namespace std;
  9.  
  10. const int ALF = 256;
  11. const int Q = 9551;
  12.  
  13.  
  14. int Hash(string text, int n)
  15. {
  16. int h = 0;
  17.  
  18. for (int i = 0; i<n; i++)
  19. {
  20. h = (ALF * h + (unsigned char)text[i]) % Q;
  21. }
  22. return h;
  23. }
  24.  
  25. bool Check(string text, string wzor, int pozycja)
  26. {
  27. for (int i = 0; i < wzor.length(); i++)
  28. if (wzor[i] != text[pozycja + i])
  29. return false;
  30. return true;
  31. }
  32.  
  33. int Last(int n)
  34. {
  35. int l = 1;
  36.  
  37. for (int i = 1; i <= n - 1; i++)
  38. {
  39. l = (ALF*l) % Q;
  40. }
  41.  
  42. return l;
  43. }
  44.  
  45. void Szukaj(string wzor, string text)
  46. {
  47.  
  48. int t = Hash(text, wzor.length());
  49. int p = Hash(wzor, wzor.length());
  50. int pozycja = 0;
  51. int d = Last(wzor.length());
  52.  
  53. for (int i = wzor.length(); i <= text.length(); i++)
  54. {
  55. pozycja = i - wzor.length();
  56. if (p == t && Check(text, wzor, pozycja))
  57. {
  58. cout << pozycja << " ";
  59. }
  60. t = (t + Q - (d * (unsigned char)text[i - wzor.length()]) % Q) % Q;
  61. t = (t * ALF + (unsigned char)text[i]) % Q;
  62. }
  63. cout << endl;
  64.  
  65. }
  66. void Read()
  67. {
  68. int liczba_przypadkow;
  69.  
  70. string file;
  71. string wzor;
  72. string linia;
  73. string text;
  74.  
  75. cin >> liczba_przypadkow;
  76. for (int i = 0; i < liczba_przypadkow; i++)
  77. {
  78.  
  79. cin >> file;
  80. cin.ignore();
  81. getline(cin, wzor);
  82. fstream plik;
  83. plik.open(file, ios::out | ios::in);
  84. while (getline(plik, linia))
  85. {
  86. text = text + linia + "\n";
  87. }
  88. plik.close();
  89. Szukaj(wzor, text);
  90. text.clear();
  91. }
  92.  
  93. }
  94.  
  95. int main()
  96. {
  97.  
  98. Read();
  99.  
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement