标签:ret def this namespace printf 0ms acm fine math
Time Limit: 15000MS | Memory Limit: 65536K | |
Total Submissions: 13157 | Accepted: 5028 |
Description
Input
Output
Sample Input
abcbabcbabcba abacacbaaaab END
Sample Output
Case 1: 13 Case 2: 6
Source
题意:求一个字符串的最长回文子串
思路:回文串其实就是以一个节点为中间,两端的字符串是相同的。之前的比较字符串相同的Hash函数是以从左到右的顺序,那么这个就再存一个从右到左的字符串的Hash值。对于每一个字符,二分左半子串的长度,分回文串的长度是奇还是偶两种情况。
1 #include <iostream> 2 #include <set> 3 #include <cmath> 4 #include <stdio.h> 5 #include <cstring> 6 #include <algorithm> 7 #include <map> 8 using namespace std; 9 typedef long long LL; 10 #define inf 0x7f7f7f7f 11 12 const int maxn = 1e6 + 5; 13 char s[maxn]; 14 unsigned long long H[maxn], p[maxn], H_rev[maxn]; 15 16 unsigned long long getH(int i, int j) 17 { 18 return H[j] - H[i - 1] * p[j - i + 1]; 19 } 20 21 unsigned long long getHrev(int i, int j) 22 { 23 return H_rev[i] - H_rev[j + 1] * p[j - i + 1]; 24 } 25 26 int main() 27 { 28 int cas = 1; 29 p[0] = 1; 30 for(int i = 1; i < maxn; i++){ 31 p[i] = p[i - 1] * 131; 32 } 33 while(scanf("%s", s + 1)){ 34 if(strcmp(s + 1, "END") == 0){ 35 break; 36 } 37 int n = strlen(s + 1); 38 H[0] = 0; 39 H_rev[n + 1] = 0; 40 for(int i = 1; i <= n; i++){ 41 H[i] = H[i - 1] * 131 + (s[i] - ‘a‘ + 1); 42 } 43 for(int i = n; i >= 1; i--){ 44 H_rev[i] = H_rev[i + 1] * 131 + (s[i] - ‘a‘ + 1); 45 } 46 47 int ans = -1; 48 for(int i = 1; i <= n; i++){ 49 int ped = min(i - 1, n - i), pst = 1; 50 while(pst < ped){ 51 int pmid = (pst + ped + 1) / 2; 52 //cout<<pmid<<endl; 53 if(getH(i - pmid, i - 1) == getHrev(i + 1, i + pmid)){ 54 // 55 pst = pmid; 56 } 57 else{ 58 ped = pmid - 1; 59 } 60 } 61 //cout<<i<<" "<<pst<<endl; 62 ans = max(ans, 2 * pst + 1); 63 int qed = min(i - 1, n + 1 - i), qst = 1; 64 while(qst < qed){ 65 int qmid = (qst + qed + 1) / 2; 66 if(getH(i - qmid, i - 1) == getHrev(i, i + qmid - 1)){ 67 68 qst = qmid; 69 } 70 else{ 71 qed = qmid - 1; 72 } 73 } 74 ans = max(ans, 2 * qst); 75 76 } 77 78 printf("Case %d: %d\n", cas++, ans); 79 } 80 81 }
标签:ret def this namespace printf 0ms acm fine math
原文地址:https://www.cnblogs.com/wyboooo/p/9817920.html