POJ 3974 Palindrome
2015-09-10 18:04
387 查看
Language: Default Palindrome
Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?" A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not. The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!". If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string. Input Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string "END" (quotes for clarity). Output For each test case in the input print the test case number and the length of the largest palindrome. Sample Input abcbabcbabcba abacacbaaaab END Sample Output Case 1: 13 Case 2: 6 Source Seventh ACM Egyptian National Programming Contest |
#include <cstring>
const int N = 2000010;
char str
;
int p
;
int min(const int & a, const int & b) {
return a < b ? a : b;
}
int main() {
int cnt = 0;
while (~scanf("%s", str), str[0] != 'E') {
int len = strlen(str);
for (int i = len; i >= 0; --i) {
str[i << 1 | 1] = str[i];
str[i << 1] = '$';
}
len = len * 2 + 1;
int id = 0, max_len = -1;
p[id] = 1;
for (int i = 1; i < len; ++i) {
if (p[id] + id > i) p[i] = min(p[id] + id - i, p[id * 2 - i]);
else p[i] = 1;
while (i - p[i] >= 0 && str[i - p[i]] == str[i + p[i]]) ++p[i];
if (p[id] + id < p[i] + i) id = i;
if (max_len < p[i]) max_len = p[i];
}
printf("Case %d: %d\n", ++cnt, max_len - 1);
}
return 0;
}
相关文章推荐
- [C++11 并发编程] 17 超时等待 - time_point
- Spring搭建框架
- linux php安装
- ajax登录请求,无法跳转
- 获取iOS设备的相关信息
- c实现面向对象
- Spring MVC之@RequestBody, @ResponseBody 详解
- mybatis实战教程(mybatis in action),mybatis入门到精通
- JUnit编写单元测试代码注意点小结
- Java对象clone
- mysql开启慢查询日志
- HDU 3613 Best Reward
- mysql 年龄段划分
- 读Swift官方文档的收获(一)
- tomcat中设置多项目共享jar;类包
- 从TCP协议的原理来谈谈rst复位攻击
- //问题:Calendar 到底是不是单例模式? Date类
- 《代码的第一行——Android》封面诞生
- 0909 关于编译原理学习的想法
- spring原理