生活随笔
收集整理的這篇文章主要介紹了
POJ 3974 Palindrome (算竞进阶习题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
hash + 二分答案
數據范圍肯定不能暴力,所以考慮哈希。
把前綴和后綴都哈希過之后,掃描一邊字符串,對每個字符串二分枚舉回文串長度,注意要分奇數和偶數
#include <iostream>
#include <cstdio>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline int lowbit(int x){ return x & (-x); }
inline int read(){int X = 0, w = 0; char ch = 0;while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){A ans = 1;for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;return ans;
}const int N = 1000005;
const int P = 131;
ull f[N], p[N], rf[N];
char s[N];
int ans, n, cnt;int solve1(int i){int l = 0, r = min(i - 1, n - i);while(l < r){int mid = (l + r + 1) >> 1;if(f[i] - f[i - mid - 1] * p[mid + 1] == rf[i] - rf[i + mid + 1] * p[mid + 1])l = mid;else r = mid - 1;}return l;
}int solve2(int i){int l = 0, r = min(i - 1, n - i + 1);while(l < r){int mid = (l + r + 1) >> 1;if(f[i - 1] - f[i - mid - 1] * p[mid] == rf[i] - rf[i + mid] * p[mid])l = mid;else r = mid - 1;}return l;
}int main(){while(1){scanf("%s", s + 1);n = strlen(s + 1);if(n == 3 && s[1] == 'E' && s[2] == 'N' && s[3] == 'D') break;full(p, 0), full(f, 0), full(rf, 0);ans = 0;p[0] = 1;for(int i = 1; i <= n; i ++){f[i] = f[i - 1] * P + (s[i] - 'a' + 1);p[i] = p[i - 1] * P;}for(int i = n; i >= 1; i --){rf[i] = rf[i + 1] * P + (s[i] - 'a' + 1);}for(int i = 1; i <= n; i ++){ans = max(ans, 2 * solve1(i) + 1);ans = max(ans, 2 * solve2(i));}printf("Case %d: %d\n", ++cnt, ans);}return 0;
}
轉載于:https://www.cnblogs.com/onionQAQ/p/10732307.html
總結
以上是生活随笔為你收集整理的POJ 3974 Palindrome (算竞进阶习题)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。