0w1

Yuki 599 回文かい

Problem Description:
You are given a string S. You are requested to split it into some substrings, and suppose you decompose it into k substring as  {s_0, s_1, .., s_{k - 1}}, then  {s_i = s_{k - 1 - i}} must hold for each  {i}. You are interested in knowing the number of ways to decompose the string s, modulo 1e9 + 7.

Constraints:
1 ≤ len(S) ≤ 1e4

Solution:
dp[i]: number of ways to decompose the substring S[0...i], so that the right side of S can map to be palindromic.
dp[i] = sum(dp[j] * (S[j...i] == S[-i...-j]) for j in 0...i)
Check whether two substrings are equal with hashing => O(1).

Code:

#include <bits/stdc++.h>

const int MOD = 1e9 + 7;
const int B = 311;

int Dp(const std::string &s) {
  std::vector<int> pb(s.size() + 1); {
    for (int i = pb[0] = 1; i <= s.size(); ++i) {
      pb[i] = 1LL * pb[i - 1] * B % MOD;
    }
  }
  std::vector<int> ph(s.size() + 1); {
    for (int i = 0; i < s.size(); ++i) {
      ph[i + 1] = (1LL * ph[i] * B + s[i]) % MOD;
    }
  }
  std::function<int(const std::vector<int>&, int, int)> gh = [&](const std::vector<int> &ph, int lb, int rb) {
    return ((ph[rb] - 1LL * ph[lb] * pb[rb - lb]) % MOD + MOD) % MOD;
  };
  std::vector<int> dp(s.size() / 2 + 1);
  for (int i = dp[0] = 1; i <= s.size() / 2; ++i) {
    for (int j = 0; j < i; ++j) {
      if (gh(ph, j, i) == gh(ph, s.size() - i, s.size() - j)) {
        (dp[i] += dp[j]) %= MOD;
      }
    }
  }
  return std::accumulate(dp.begin(), dp.end(), 0, [&](int x, int y) { return (x + y) % MOD; });
}

signed main() {
  std::ios::sync_with_stdio(false);
  std::string S;
  std::cin >> S;
  std::cout << Dp(S) << std::endl;
  return 0;
}