poj 3974
2015-07-05 22:24
120 查看
Manacher算法, 用来解决 最长回文子串 一类问题,俗称马拉车算法,时间复杂度 O(n)O(n)
#include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> const int maxl = 1000005; const char end[5] = "END"; #define clear(arr) memset(arr,0,sizeof(arr)) char ch[maxl], s[maxl<<1]; int sl, par[maxl<<1]; void init() { int l = strlen(ch); clear(s), clear(par); for(int i = 0; i < l; i++) s[i<<1|1] = ch[i], s[i<<1] = 255; sl = l<<1|1, s[sl-1] = 255; } int solve() { int ret = 0; for(int i = 1, id = 0, mx = 0; i < sl-1; i++) { par[i] = (i < mx)?(std::min(mx-i,par[id*2-i])):1; #define Check(t) ((t)-par[t] >= 0 && (t)+par[t] < sl) while(Check(i) && s[i-par[i]] == s[i+par[i]]) par[i]++; if(i + par[i] > mx) id = i, mx = i + par[i]; ret = std::max(par[i] - 1, ret); } return ret; } int main() { int T = 0; #ifndef ONLINE_JUDGE freopen("poj3974.in","r",stdin); freopen("poj3974.out","w",stdout); #endif while(scanf("%s",ch) != EOF) { if(!strcmp(ch, end)) break; printf("Case %d: ",++T); init(), printf("%d\n",solve()); } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); #endif return 0; }
相关文章推荐
- apache的安装过程
- [华为机试练习题]60.水仙花数
- Spring 事件机制
- poj 3974 分类: poj templates 2015-07-05 22:24 18人阅读 评论(0) 收藏
- VC CListCtrl 第一列列宽自适应
- Android native Socket实现
- Ubuntu 14.04(32位) Android Studio
- hihocoder Lucky Substrings
- Windows下的各种畸形目录和特殊文件
- 六、通知机制
- Unity3D跑酷游戏开发-无尽的道路
- MySQL增删改查
- 对象引用前加const报错:不能将“this”指针从“const a”转换为“a
- 设计模式之建造者模式
- hamcrest自定义BaseMatcher
- Xcode 使用中的技巧
- Java Calendar实现控制台日历
- 15-07-03 语句- for () 循环语句-穷举法
- CListCtrl自适应宽度
- Servlet.service() for servlet jsp threw exception