跳到正文

题解

题解:P11276 第一首歌

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

文章信息

收录
2025年12月12日
更新
2026年7月15日
篇幅
约 3 分钟
题目
P11276

版本

  1. v1当前

更新:原来哈希被卡了,换了一份新的代码。

哈希模板。

容易发现,构造出来的字符串的形式为:两个 ss,共享长度大于等于 00 的部分。

这个部分很容易发现是第一个 ss 的后缀和第二个 ss 的前缀,那么我们考虑枚举这个重叠部分的长度。设当前枚举的长度为 ll,那么如果 s1…l=sn−l+1…ns_{1 \ldots l} = s_{n - l + 1 \ldots n},这表明这个长度合法,取最大的 ll 即可(ss 是 tt 的最长 border),这个部分可以使用字符串哈希。

我们要注意,长度是 0∼n−10 \sim n - 1 枚举的,因为一个字符串的 border 不能是它本身。

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

代码如下:

C++
#include <bits/stdc++.h>

#define int long long 

const int N = 1e5 + 6;

using ull = int;

constexpr int P = 1e9 + 7;

void solve() {
    std::string s;
    std::cin >> s;
    int n = (int)s.size();
    s = " " + s;
    std::vector<ull> pw(n + 1, 0), hsh(n + 1, 0);
    pw[0] = 1;
    for (int i = 1; i <= n; ++i) {
        pw[i] = pw[i - 1] * 233 % P;
    }
    for (int i = 1; i <= n; ++i) {
        hsh[i] = hsh[i - 1] * 233 + s[i] - 'a';
        hsh[i] %= P;
    }
    auto get = [&](int l, int r) -> ull {
        if (l > r) return 0;
        return ((hsh[r] - hsh[l - 1] * pw[r - l + 1] % P) % P + P) % P;
    };
    for (int i = n - 1; i >= 0; --i) {
        if (get(1, i) == get(n - i + 1, n)) {
            std::vector<char> ans(2 * n - i + 1, 0);
            for (int i = 1; i <= n; ++i) {
                ans[i] = s[i];
            }
            for (int j = n - i + 1; j <= n - i + 1 + n - 1; ++j) {
                ans[j] = s[j - (n - i + 1) + 1];
            }
            for (int j = 1; j <= 2 * n - i; ++j) {
                std::cout << ans[j];
            }
            return;
        }
    }
}

int32_t main() {
  std::ios::sync_with_stdio(0);
  std::cin.tie(0), std::cout.tie(0);

  int t;
  // std::cin >> t;
  t = 1;

  while (t--) {
    solve();
  }

  return 0;
}
原文