fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define len 7
  6. int base=10;
  7. int power[len];
  8.  
  9. void init()
  10. {
  11. power[0]=1;
  12. for(int i=1;i<len;i++)
  13. {
  14. power[i]=power[i-1]*base;
  15. }
  16. }
  17.  
  18. int get_index(char ch)
  19. {
  20. return ch-'0';
  21. }
  22.  
  23. void prefixHash(string s,vector<int> &ph)
  24. {
  25. int n=ph.size();
  26. ph[0]=get_index(s[0]);
  27. for(int i=1;i<n;i++)
  28. {
  29. ph[i]=ph[i-1]*base+get_index(s[i]);
  30. }
  31. }
  32.  
  33. int calcHash(int l,int r,vector<int> &ph)
  34. {
  35. if(l==0) return ph[r];
  36. return ph[r]-(ph[l-1]*power[r-l+1]);
  37. }
  38.  
  39. int main()
  40. {
  41. init();
  42. //string s="123456";
  43. string txt="1211212133333333333";
  44. string pat="121";
  45. int n=txt.size(),m=pat.size();
  46.  
  47. vector<int> ph1(n),ph2(m);
  48. prefixHash(txt,ph1);
  49. prefixHash(pat,ph2);
  50.  
  51.  
  52. for(int i=0;i+m<=n;i++) /// i=3
  53. {
  54. int x=calcHash(i,i+m-1,ph1);
  55. int y=calcHash(0,2,ph2);
  56. if(x==y)
  57. {
  58. cout << "Found " << pat << " at i=" << i << endl;
  59. }
  60. }
  61. //for(int i=0;i<n;i++) cout << ph[i] << endl;
  62. //cout << calcHash(2,4,ph);
  63.  
  64.  
  65.  
  66.  
  67. return 0;
  68. }
  69.  
  70. /**
  71. 12112121
  72. **/
  73.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Found 121 at i=0
Found 121 at i=3
Found 121 at i=5