题目描述
JB hates solving string problems. Therefore, when his friend Potato gives him a string problem to solve, he immediately gives it to you and continues playing Genshin Impact, the greatest game in the world.
题意
给一个字符串,输出每一字符的一个字典序最大的子串,这个子串以当前位置的字符结尾
输入:
pbpbppb
输出:
1 1
1 2
1 3
1 4
1 5
5 6
5 7
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000012;
int n, m;
string s;
int nt[maxn];
int head = 0;//字典序最大的子串的头部
void expend_nt(int frm, char c){//更新nt数组
if(frm == 0){
nt[frm+1] = 0;
return;
}
int p = nt[frm];
while(p && s[head+p+1] != c) p = nt[p];
if(s[head+p+1] != c) nt[frm+1] = 0;
else nt[frm+1] = p + 1;
}
void solve() {
cin >> s; n = s.size();
s = '0' + s;
nt[1] = 0;
cout << "1 1\n";
int lst = 1;//当前nt数组停留的初始位置
//本题是利用kmp中的nt数组,来标记当前字母c和之前最长的子串中每个c字母之后一位字母的比较,如果子串中s[now+1]小于c,则让len变为x+1,接着进行下面的比较,直到子串中所有的c字母匹配完了
//nt数组里面记录的是当前最长子串的nt数组
for(int i=2;i<=n;i++){
int x = lst;//nt数组的位置
int len = lst + 1;//字典序最大的字串长度
// cout<<x<<' '<<len<<endl;
while(x > 0){
if(s[i] > s[i-lst+x]) len = x + 1;
if(nt[x] > x/2){
int d = x - nt[x];
x = x % d + d;
}else x = nt[x];
}
if(s[i] > s[i-lst]) len = 1;
head = i - len;
expend_nt(len-1, s[i]);
//如果不清楚输出每次的nt数组就可以明白
// for(int j=1;j<=n;j++){
// cout<<nt[j]<<' ';
// }
// cout<<endl;
lst = len;
cout << i-len+1 <<' '<< i << '\n';
}
}
signed main() {
solve();
return 0;
}