[POI2006] OKR-Periods of Words——最大周期长度(扩展最小周期长度)

[POI2006] OKR-Periods of Words------最大周期长度(扩展最小周期长度)

原题链接\]([P3435 \[POI2006\] OKR-Periods of Words - 洛谷 \| 计算机科学教育新生态 (luogu.com.cn)](https://www.luogu.com.cn/problem/P3435)) *** ** * ** *** #### 字符串的周期 讲这道题之前,我们先聊一聊字符串的周期。我们要明确**周期** 和**border**两个概念 **周期** > 对字符串 s s s和 0 \< p ≤ ∣ s ∣ 0\ 对字符串 s s s和 0 \< p \< ∣ s ∣ 0\

思路

现在我们回到该题:

该题就是让我们求字符串 s 1 s_1 s1的最小周期

代码

代码如下

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 10;

char c[N];
int ne[N];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    // 字符串下标从1开始
    cin >> n >> c + 1;
    // 获取next数组
    for (int i = 2, j = 0; i <= n; i ++) {
        while (j && c[i] != c[j + 1])
            j = ne[j];
        if (c[i] == c[j + 1]) {
            j ++;
            ne[i] = j;
        }
    }
    cout << n - ne[n];

    return 0;
}

扩展:最大周期长度

让每一个next数组的值都是最短前缀

核心代码

cpp 复制代码
int j = n;
// 转换为最短前缀
while (ne[j]) 
    j = ne[j];
// 记忆化存储
if (ne[i])  ne[i] = j;
// 最大周期长度
len = n - j;

例题

\[POI2006\] OKR-Periods of Words\]([P3435 \[POI2006\] OKR-Periods of Words - 洛谷 \| 计算机科学教育新生态 (luogu.com.cn)](https://www.luogu.com.cn/problem/P3435)) > **分析** > > 求每个子串的最大周期长度 > > **样例分析** > > bab 2 > > baba 2 > > babab 4 > > bababa 4 > > bababab 6 > > babababa 6 **参考代码** ```cpp #include using namespace std; const int N = 1e6 + 10; typedef long long LL; char s[N]; LL ne[N]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n >> s + 1; for (int i = 2, j = 0; i <= n; i ++) { while (j && s[i] != s[j + 1]) j = ne[j]; if (s[i] == s[j+1]) j ++; ne[i] = j; } LL ans = 0; for (int i = 2; i <= n; i ++) { int j = i; while (ne[j]) { j = ne[j]; } if (ne[i]) ne[i] = j; ans += i-j; } cout << ans << endl; return 0; } ```

相关推荐
nenchoumi311923 分钟前
UE5 学习系列(一)创建一个游戏工程
c++·学习·游戏·ue5
温宇飞1 小时前
C++ 作用域和标识符查找规则详解
c++
随意0231 小时前
STL 1 容器
开发语言·c++
cpp加油站1 小时前
拒绝切换IDE,10分钟让Trae编辑器化身C++神器,智能补全、编译调试一网打尽
c++·ai编程·trae
啊我不会诶2 小时前
篮球杯软件赛国赛C/C++ 大学 B 组补题
c语言·c++
l1t2 小时前
DeepSeek辅助实现的DuckDB copy to自定义函数
数据库·c++·人工智能
Bardb3 小时前
01__C++入门
c++·qt
weixin_457665394 小时前
C++11新标准
开发语言·c++
奔跑吧邓邓子5 小时前
解锁Vscode:C/C++环境配置超详细指南
c语言·c++·vscode·配置指南
虾球xz5 小时前
CppCon 2015 学习:Reactive Stream Processing in Industrial IoT using DDS and Rx
开发语言·c++·物联网·学习