1040 Longest Symmetric String (25 分)
Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?
, the longest symmetric sub-string is s PAT&TAP s
, hence you must output 11
.
Input Specification:
Each input file contains one test case which gives a non-empty string of length no more than 1000.
Output Specification:
For each test case, simply print the maximum length in a line.
Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11
最大回文串,虽然可以暴力写,但是那样太无聊了。
马拉车来一波。
1 #include <bits/stdc++.h> 2 #define N 1000000 3 using namespace std; 4 int p[N];//保存当前点的半径 5 6 7 int Manacher(string s1){ 8 string s = "$#"; 9 for(int i = 0; i < s1.length(); i++){ 10 s += s1[i]; 11 s += '#'; 12 } 13 int id=0;//表示到目前为止能到达最远的距离的点的位置 14 int clen=0;//表示最长半径 15 int mx = 0;//表示最远的距离 16 for(int i = 1; i < s.length(); i++){ 17 p[i] = mx < i?1:min(mx-i, p[id*2-i]); 18 while(s[i-p[i]] == s[i+p[i]]) 19 p[i]++; 20 21 if(mx < i+p[i]){ 22 mx = i + p[i]; 23 id = i; 24 } 25 26 if(clen < p[i]){ 27 clen = p[i]; 28 } 29 } 30 return clen-1; 31 } 32 33 34 string s; 35 int main() { 36 getline(cin,s); 37 cout<<Manacher(s)<<endl; 38 return 0; 39 }