Seekthe Name, Seek the Fame
KMP跳border链输出所有公共前后缀长
正文
// 原题:https://oj.yecheng.tv/p/T1458
// 题意:每行一个字符串(读到 EOF),输出一行所有既是其前缀又是其后缀的子串长度,递增排列。
// 思路:求前缀函数后从 n 沿 nxt 链一直跳到 0,链上每个值都是一组公共前后缀长度,倒序输出即递增。
// 复杂度:O(单串长度) 时间 / O(单串长度) 空间
// 易错点:答案要包含串自身长度 n;用栈/数组收集后反向输出,直接正序打印会得到递减序列。
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
while(cin>>s){
int n=(int)s.size();
vector<int> nxt(n+1,0);
for(int i=1;i<n;i++){
int j=nxt[i];
while(j>0&&s[i]!=s[j]) j=nxt[j];
if(s[i]==s[j]) j++;
nxt[i+1]=j;
}
vector<int> out;
for(int x=n;x>0;x=nxt[x]) out.push_back(x);
for(int i=(int)out.size()-1;i>=0;i--){
if(i!=(int)out.size()-1) cout<<' ';
cout<<out[i];
}
cout<<'\n';
}
return 0;
}
一本通·提高篇的其它内容
- 活动安排
- 种树
- 喷水装置
- 加工生产调度
- 智力大冲浪
- 数列极差
- 数列分段
- 线段
- 家庭作业
- 钓鱼
- 糖果传递
- 愤怒的牛
- Best Cow Fences
- 曲线
- 数列分段 II
- 扩散
- 灯泡
- 传送带
- 数的划分
- 生日蛋糕
- 小木棍
- Addition Chains
- 埃及分数
- 平板涂色
- 质数方阵
- 靶形数独
- 电路维修
- 魔板
- Knight Moves
- 棋盘游戏
- Keyboarding
- 移动玩具
- 山峰和山谷
- Oulipo
- 图书管理
- Power Strings
- Friends
- A Horrible Poem
- Beads
- Antisymmetry
- 门票
- 收集雪花
- 剪花布条
- Power Strings
- Radio Transmission
- OKR-Periods of Words
- 似乎在梦中见过的样子
- Censoring
- Phone List
- The XOR Largest Pair
- Nikitosh 和异或
- Immediate Decodability
- L 语言
- Secret Message 秘密信息
- 背单词
- The Xor-longest Path
- Keywords Search
- 玄武密码
- Censoring
- 单词