[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; } ```

相关推荐
小苗卷不动4 小时前
OJ练习之加减(中等偏难)
c++
我能坚持多久4 小时前
String类常用接口的实现
c语言·开发语言·c++
智者知已应修善业5 小时前
【数字稳压控制DAC/TLC5615驱动】2023-5-27
c++·经验分享·笔记·算法·51单片机
t***5445 小时前
Orwell Dev-C++和Embarcadero Dev-C++哪个更稳定
开发语言·c++
代码中介商5 小时前
C++运行时多态深度解析:从原理到实践
开发语言·c++·多态·虚函数
代码中介商5 小时前
C++ 继承与派生深度解析:存储布局、构造析构与高级特性
开发语言·c++·继承·派生
谭欣辰5 小时前
C++ 控制台跑酷小游戏2.0
开发语言·c++·游戏程序
Wild_Pointer.6 小时前
C++:内存顺序(Memory Order)的概念以及使用
c++
并不喜欢吃鱼6 小时前
从零开始C++----七.继承相关模型,解析多继承与菱形继承问题(下篇)
开发语言·c++
进击的荆棘6 小时前
递归、搜索与回溯——二叉树中的深搜
数据结构·c++·算法·leetcode·深度优先·dfs