-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanachar.cpp
36 lines (29 loc) · 1.12 KB
/
manachar.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <bits/stdtr1c++.h>
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define dbg(x) cout << #x << " = " << x << endl
using namespace std;
/*** Manacher's algorithm to generate longest palindromic substrings for all centers ***/
/// When i is even, pal[i] = largest palindromic substring centered from str[i / 2]
/// When i is odd, pal[i] = largest palindromic substring centered between str[i / 2] and str[i / 2] + 1
vector <int> manacher(char *str){ /// hash = 784265
int i, j, k, l = strlen(str), n = l << 1;
vector <int> pal(n);
for (i = 0, j = 0, k = 0; i < n; j = max(0, j - k), i += k){
while (j <= i && (i + j + 1) < n && str[(i - j) >> 1] == str[(i + j + 1) >> 1]) j++;
for (k = 1, pal[i] = j; k <= i && k <= pal[i] && (pal[i] - k) != pal[i - k]; k++){
pal[i + k] = min(pal[i - k], pal[i] - k);
}
}
pal.pop_back();
return pal;
}
int main(){
char str[100];
while (scanf("%s", str)){
vector<int> v = manacher(str);
for (int i=0;i<v.size();i++) printf("%d ",v[i]);
puts("");
}
return 0;
}