跳到正文

算法·理论

【NOIP2025】字符串模板

andysheng约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年11月27日
收录
2026年4月25日
更新
2026年11月17日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

Hash

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int P = 131;
unsigned long long f[N], p[N];
int n;
string str;

void Hash_prework()
{
    n = str.size() - 1;
    p[0] = 1;
    for(int i = 1; i <= n; i++)
    {
        f[i] = f[i - 1] * P + str[i] - '0' + 1;
        p[i] = p[i - 1] * P;
    }
}

int Hash_query(int l, int r)
{
    return f[r] - f[l - 1] * p[r - l + 1];
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> str, str = " " + str;
    Hash_prework();
    int m;
    cin >> m;
    for(int i = 1; i <= m; i++)
    {
        int l1, r1, l2, r2;
        cin >> l1 >> r1 >> l2 >> r2;
        if(Hash_query(l1, r1) == Hash_query(l2, r2)) cout << "Yes\n";
        else cout << "No\n";
    }
    return 0;
}

最小表示法

C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    string str;
    cin >> str, str = " " + str;
    for(int i = 1; i <= n; i++) str += str[i];
    int i = 1, j = 2, k = 0;
    while(i <= n && j <= n)
    {
        for(k = 0; k < n && str[i + k] == str[j + k]; k++);
        if(k == n) break;
        if(str[i + k] > str[j + k])
        {
            i = i + k + 1;
            if(i == j) j++;
        }
        else
        {
            j = j + k + 1;
            if(i == j) i++;
        }
    }
    int ans = min(i, j);
    for(int i = ans; i <= ans + n - 1; i++) cout << str[i];
    cout << '\n';
    return 0;
}
原文