第 46 届 ICPC 国际大学生程序设计竞赛亚洲区域赛(沈阳) M题 题解

题目描述

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值