洛谷 P3805 manacher算法
生活随笔
收集整理的這篇文章主要介紹了
洛谷 P3805 manacher算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
鏈接:https://www.luogu.org/problemnew/show/P3805
思路:模板,直接上馬拉車
代碼:
1 //#include<bits/stdc++.h> 2 #include<iostream> 3 #include<vector> 4 #include<stack> 5 #include<string> 6 #include<cstdio> 7 #include<algorithm> 8 #include<queue> 9 #include<map> 10 #include<set> 11 #include<cmath> 12 #define inf 0x3f3f3f3f 13 using namespace std; 14 typedef long long ll; 15 const ll M = ll(1e7) * 3 + 5; 16 string s; 17 string s2; 18 ll len[M]; 19 string init(string s) 20 { 21 s2.clear(); 22 s2 += '@'; 23 for (ll i = 0; i < s.size(); i++) 24 { 25 s2 += '#'; 26 s2 += s[i]; 27 } 28 //s2 += s[s.size() - 1]; 29 s2 += '#'; 30 // s2 += '$'; 31 // s2 += '\0'; 32 return s2; 33 } 34 ll Manacher(string s) 35 { 36 ll p0 = 0, mx = 0, ans = 0; 37 for (ll i = 1; i < s.size(); i++) 38 { 39 if (i < mx) 40 len[i] = min(mx - i, len[2 * p0 - i]); 41 else 42 len[i] = 1; 43 while (s[i - len[i]] == s[i + len[i]]) 44 len[i]++; 45 if (i + len[i] > mx) 46 { 47 mx = len[i] + i; 48 p0 = i; 49 } 50 ans = max(ans, len[i]); 51 } 52 return ans - 1; 53 } 54 int main() 55 { 56 while (cin >> s) 57 { 58 s = init(s); 59 //cout << s << endl; 60 cout << Manacher(s) << endl; 61 } 62 return 0; 63 }備注:在初始化原串的時候要注意還需要再加一個不同的字符,我這里用的是@,防止馬拉車的時候上溢,詳情可見這篇博客
轉載于:https://www.cnblogs.com/harutomimori/p/10660935.html
總結
以上是生活随笔為你收集整理的洛谷 P3805 manacher算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有人用过BamHI和PagI对目的基因进
- 下一篇: 都市夜未眠