题解:P13270 【模板】最小表示法

· · 题解

循环同构

在了解最小表示法前,我们需要知道什么是循环同构。

所谓循环同构就是指当字符串 S 满足使 S 分为前后两部分: A、B 如果 B+A=T 则称 S 和 T 为循环同构。

最小表示法

最小表示法就是字符串 S 循环同构的所有字符串中字典序最小的字符串。

思路

这道题首先考虑到的是 simple 但本题给出的数据↓

对于全部数据,1\le n\le10 7,字符串 s 仅包含小写英文字母(ASCII 97∼122)。

我们便可以放弃 O(N^2) 的算法,此时我们便要写一个正经的 最小表达式 ,时间复杂度为 O(N) 过此题又是有惊无险。

原理

(其实 oiwiki 上有)

定义 date.first=1、date.second=2、k=0 。

通过不断比对以 date.first 为首的字符串和以 date.second 为首的字符串。

如果前 k 位相同便让 date.first=date.first+k+1

注意:当 date.first=date.second 时,使 date.first=date.first+1,且最终选取两者之中较小的一个作为结果。

详细代码

#include"bits/stdc++.h"
#define ll long long
using namespace std;
template<typename T>inline void read(T&x) {
    char c;
    int sign = 1;
    x = 0;
    do {
        c = getchar();
        if (c == '-') sign = -1;
    } while (!isdigit(c));
    do {
        x = x * 10 + c - '0';
        c = getchar();
    } while (isdigit(c));
    x *= sign;
}
// 快读
const int N = 1e7 + 5;
// N代表题目中n的范围
char a[N << 1];
// 建立N的两倍的a数组
ll n;
int main() {
    read(n);
    for (int i = 1; i <= n; i++) {
        a[i] = getchar();// 读入
        a[i + n] = a[i];// 预处理
    }
    ll date_first = 1, date_second = 2, k = 0;
    while (date_first <= n && date_second <= n && k <= n) {
        if (a[date_first + k] == a[date_second + k])
            k++;
        else {
            if (a[date_first + k] > a[date_second + k])
                date_first += k + 1;
            else
                date_second += k + 1;
            if (date_first == date_second)
                date_second++;
            k = 0;
        }
    }
// 以上再【原理】中有解释
    int vis;
    if (date_first < date_second)
        vis = date_first;
    else vis = date_second;
// 选择两者之中较小的一位
    for (int i = 0; i < n; i++)
        cout << a[vis + i];
//输出
    return 0;
}