嘘~ 正在从服务器偷取页面 . . .

洛谷P3435 [POI2006] OKR-Periods of Words 题解


洛谷P3435 [POI2006] OKR-Periods of Words 题解

题目链接:P3435 [POI2006] OKR-Periods of Words

题意

对于一个仅含小写字母的字符串 \(a\)\(p\)\(a\) 的前缀且 \(p\ne a\),那么我们称 \(p\)\(a\) 的 proper 前缀。

规定字符串 \(Q\)(可以是空串)表示 \(a\) 的周期,当且仅当 \(Q\)\(a\) 的 proper 前缀且 \(a\)\(Q+Q\) 的前缀。

例如 ababab 的一个周期,因为 ababab 的 proper 前缀,且 ababab+ab 的前缀。

求给定字符串所有前缀的最大周期长度之和。

\(1\le |a| \le 10^6\)

考虑如何最大化周期 \(Q\)

对于某个前缀,例如 \(s = \tt{aabaaaab}\)

不难发现它的最长周期就是 \(\tt{aabaa}\)

仔细观察 \(\tt{\color{red}{aab}\color{blue}{aa}\color{red}{aab}}\)

其实这个 \(Q = \tt{\color{red}{aab}\color{blue}{aa}}\)

就是 \(s\)最短非空border \(\tt{\color{red}{aab}}\) 加上中间那一段东西

这样对于每个 \(i\) ,我们只要找到它的最短border就好了

这个东西可以通过跳fail数组实现

但是如果每次都暴力跳,显然会有很多重复步骤

这个跳的过程,是不是很熟悉?并查集也是这么跳的对吧!

并查集可以路径压缩,这里fail数组我们也可以路径压缩。

时间复杂度 \(O(n)\)

代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <random>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
#define N (int)(1e6+15)

char s[N];
int n,res,fail[N];
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    // freopen("check.in","r",stdin);
    // freopen("check.out","w",stdout);
    cin >> n >> (s+1);
    for(int i=2,j=0; i<=n; i++)
    {
        while(j&&s[i]!=s[j+1])j=fail[j];
        if(s[i]==s[j+1])++j;
        fail[i]=j;
    }
    for(int i=1,j; i<=n; i++)
    {
        j=i;
        while(fail[j]) j=fail[j];
        if(fail[i]!=0) fail[i]=j;
        res+=(i-j);
    }
    cout << res << '\n';
    return 0;
}

文章作者: q779
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 q779 !
评论
  目录