manacher和字典树
作者:互联网
manacher求最大回文串,
1 char str[N]; 2 ll pre[N]; 3 ll ans = 0; 4 void getstr(string s){ 5 int dex = 0; 6 ll len = (ll)s.size() * 2 + 1; 7 for (ll i = 0; i <len ; ++i){ 8 if (i & 1){ 9 str[i] = s[dex++]; 10 } 11 else{ 12 str[i] = '#'; 13 } 14 }//在字符串中间插入特殊字符,方便后面的计算 15 } 16 void manacher(string s){ 17 getstr(s); 18 ll c = -1;//中点 19 ll r = -1;//半径的下一个位置 20 ll len = (ll)s.size() * 2 + 1; 21 for (ll i = 0; i < len; ++i){ 22 pre[i] = r>i ? min(r-i,pre[c*2-i]) : 1;//在所有的情况下不需要往外扩的长度 23 while (i + pre[i] < len&&i - pre[i] >= 0){ 24 if (str[i + pre[i]] == str[i - pre[i]]){ 25 pre[i]++; 26 } 27 else 28 break; 29 } 30 if (i + pre[i]>r){ 31 r = pre[i] + i; 32 c = i; 33 } 34 ans = max(ans, pre[i] - 1); 35 } 36 } 37 int main(){ 38 string s; 39 cin >> s; 40 manacher(s); 41 cout << ans << endl; 42 system("pause"); 43 return 0; 44 }
字典树,一种树的结构,可以快速的查询和插入
1 int nex[N][27]; 2 int isend[N]; 3 int cnt = 0; 4 void add(string s) { 5 int now = 0; 6 for (int i = 0; i < s.size(); ++i) { 7 int d = s[i] - 'a'; 8 if (!nex[now][d]) { 9 nex[now][d] = ++cnt; 10 } 11 now = nex[now][d]; 12 } 13 isend[now] = true; 14 } 15 bool check(string s) { 16 int now = 0; 17 for (int i = 0; i < s.size(); ++i) { 18 int d = s[i] - 'a'; 19 if (!nex[now][d]) 20 return false; 21 now = nex[now][d]; 22 } 23 return isend[now]; 24 } 25 int main() { 26 int n; 27 while (n--) { 28 string s; 29 cin >> s; 30 add(s); 31 } 32 return 0; 33 }
标签:pre,string,int,manacher,ll,nex,now,字典 来源: https://www.cnblogs.com/xuanru/p/16475830.html