標籤:輸入 code insert black 迴文 模板 字元 enter ext
1089 最長迴文子串 V2(Manacher演算法) 基準時間限制:1 秒 空間限制:131072 KB 分值: 0 難度:基礎題 迴文串是指aba、abba、cccbccc、aaaa這種左右對稱的字串。輸入一個字串Str,輸出Str裡最長迴文子串的長度。 Input
輸入Str(Str的長度 <= 100000)
Output
輸出最長迴文子串的長度L。
Input樣本
daabaac
Output樣本
5
馬拉車演算法的模板題
也算是又進一步理解馬拉車演算法了.
1 //馬拉車演算法 2 #include <bits/stdc++.h> 3 #define N 1000000 4 using namespace std; 5 6 int resLen; 7 int p[N]; 8 int Manacher(string s) { 9 // Insert ‘#‘10 string t = "$#";11 for (int i = 0; i < s.length(); ++i) {12 t += s[i];13 t += "#";14 }15 // Process t16 int mx = 0, id = 0, resLen = 0, resCenter = 0;17 for (int i = 1; i < t.length(); ++i) {18 //將重複找過的子串直接賦值,多的部分再自行分析19 p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;20 //多的部分自行分析21 while (t[i + p[i]] == t[i - p[i]]) 22 ++p[i];23 24 //更新最長到達右邊的位置並且記錄當前位置25 if (mx < i + p[i]) {26 mx = i + p[i];27 id = i;28 }29 //更新最長子串長度,以及半徑長和當前位置30 if (resLen < p[i]) {31 resLen = p[i];32 // resCenter = i;33 }34 }35 // return s.substr((resCenter - resLen) / 2, resLen - 1);36 return resLen - 1;37 }38 39 string s;40 int main() {41 cin>>s;42 cout<<Manacher(s)<<endl;43 return 0;44 }
1089 最長迴文子串