<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>

<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aab&quot;
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning [&quot;aa&quot;,&quot;b&quot;] could be produced using 1 cut.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;a&quot;
<strong>Output:</strong> 0
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;ab&quot;
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 2000</code></li>
	<li><code>s</code> consists of lowercase English letters only.</li>
</ul>

class Solution {
 public:
  std::array<std::vector<int>, 26> locations{};
  std::array<bool, 2000> seen{false};

  constexpr Solution() {
    for (auto& vec : locations) {
      vec.reserve(2000);
    }
  }

  constexpr static auto check(const std::string& s, int l, int r) -> bool {
    while (l < r) {
      if (s[l++] != s[r--]) {
        return false;
      }
    }
    return true;
  }

  auto minCut(const std::string& s) -> int {
    int n = static_cast<int>(s.size());
    for (int i = n - 1; i >= 0; --i) {
      locations[s[i] - 'a'].push_back(i);
    }
    using p = std::pair<int, int>;
    constexpr auto cmp = [](const p& lhs, const p& rhs) {
      return lhs.first > rhs.first ||
             (lhs.first == rhs.first && lhs.second < rhs.second);
    };
    std::priority_queue<p, std::vector<p>, decltype(cmp)> pq;
    pq.emplace(0, 0);
    while (!pq.empty()) {
      auto [cuts, idx] = pq.top();
      pq.pop();
      for (int idx2 : locations[s[idx] - 'a']) {
        if (seen[idx2]) {
          continue;
        }
        if (check(s, idx, idx2)) {
          if (idx2 + 1 == n) {
            return cuts;
          }
          pq.emplace(cuts + 1, idx2 + 1);
          seen[idx2] = true;
        }
      }
    }
    return -1;
  }
};
16826