Advertisement
mickypinata

PROG-T1154: Longest Repeated Substring

Jul 9th, 2020
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5. #define lli long long
  6. const lli PB = 1e9 + 7;
  7.  
  8. int len, tr;
  9. bool Repeated(char str[], int x){
  10.     map<lli, int> mp;
  11.     lli base = 1;
  12.     lli hsh = 0;
  13.     // Hash first substring
  14.     for(int i = 0; i < x; ++i){
  15.         hsh *= PB;
  16.         hsh += str[i];
  17.         if(i != 0){
  18.             base *= PB;
  19.         }
  20.     }
  21.     mp.insert(make_pair(hsh, 1));
  22.     // Rolling hash
  23.     for(int i = x; i < len; ++i){
  24.         hsh -= str[i - x] * base;
  25.         hsh *= PB;
  26.         hsh += str[i];
  27.         if(mp.find(hsh) == mp.end()){
  28.             mp.insert(make_pair(hsh, 1));
  29.         } else {
  30.             ++mp[hsh];
  31.             if(mp[hsh] >= tr){
  32.                 return true;
  33.             }
  34.         }
  35.     }
  36.     return false;
  37. }
  38.  
  39. int main(){
  40.  
  41.     scanf("%d", &len);
  42.     scanf("%d", &tr);
  43.  
  44.     char str[len + 2];
  45.     scanf(" %s", str);
  46.  
  47.     int l = 1;
  48.     int r = len;
  49.     int mx = 1;
  50.     while(l <= r){
  51.         int m = (l + r) / 2;
  52.         if(Repeated(str, m)){
  53.             mx = max(mx, m);
  54.             l = m + 1;
  55.         } else {
  56.             r = m - 1;
  57.         }
  58.     }
  59.  
  60.     cout << mx;
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement