Josif_tepe

Untitled

Aug 30th, 2026
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cstring>
  5. #include <map>
  6. using namespace std;
  7. typedef long long ll;
  8.  
  9. string manachers_algorithm(string s) {
  10.     if(s.empty()) {
  11.         return "";
  12.     }
  13.    
  14.     string t = "^";
  15.     for(char c: s) {
  16.         t += "#";
  17.         t += c;
  18.     }
  19.     t += "#$";
  20.    
  21.     int n = (int) t.length();
  22.     vector<int> P(n, 0);
  23.     int C = 0, R = 0;
  24.     int max_length = 0, center_idx = 0;
  25.    
  26.     for(int i = 1; i < n - 1; i++) {
  27.         int i_mirror = 2 * C - i;
  28.        
  29.         if(R > i) {
  30.             P[i] = min(R - i, P[i_mirror]);
  31.         }
  32.        
  33.         while(t[i + 1 + P[i]] == t[i - 1 - P[i]]) {
  34.             P[i]++;
  35.         }
  36.        
  37.         if(i + P[i] > R) {
  38.             C = i;
  39.             R = i + P[i];
  40.         }
  41.        
  42.         if(P[i] > max_length) {
  43.             max_length = P[i];
  44.             center_idx = i;
  45.         }
  46.     }
  47.     int S = (center_idx - max_length) / 2;
  48.     return s.substr(S, max_length);
  49. }
  50. int main() {
  51.     ios_base::sync_with_stdio(false);
  52.     string s;
  53.     cin >> s;
  54.    
  55.     cout << manachers_algorithm(s) << endl;
  56.     return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment