解題思路
先計算深度至多 H、峰數恰 P 的合法括號序列數 f(H),答案為 f(H)-f(H-1)。
DP 記已放字元數、目前高度、峰數與上一字元是否為左括號。放左括號使高度加一且不得超過上限;放右括號要求高度>0,若上一字元是左括號就新增一個峰。
已用左括號數可由 (長度+高度)/2 算出,確保不超過 n。最後高度 0 且峰數 P 才計入。
時間 O(n(H+1)(P+1)),空間 O((H+1)(P+1)),Python用稀疏狀態表。
Step-by-step animation
教學例子:n=3 的五個合法序列依峰數分類。
步驟 1 / 3
步驟 1
n=3 的五個合法序列依峰數分類。
((()))
(()())
(())()
()(())
()()()
- 狀態
- 共5
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, H, P;
cin >> n >> H >> P;
const long long M = 1000000007;
auto solve = [&](int cap) {
if (cap < 0)
return 0LL;
int z = (cap + 1) * (P + 1) * 2;
vector<long long> dp(z);
auto ix = [&](int h, int p, int o) { return (h * (P + 1) + p) * 2 + o; };
dp[ix(0, 0, 0)] = 1;
for (int t = 0; t < 2 * n; t++) {
vector<long long> nd(z);
for (int h = 0; h <= cap; h++)
for (int p = 0; p <= P; p++)
for (int o = 0; o < 2; o++) {
long long w = dp[ix(h, p, o)];
if (!w)
continue;
if (h < cap && (t + h) / 2 < n)
nd[ix(h + 1, p, 1)] = (nd[ix(h + 1, p, 1)] + w) % M;
if (h > 0 && p + o <= P)
nd[ix(h - 1, p + o, 0)] = (nd[ix(h - 1, p + o, 0)] + w) % M;
}
dp.swap(nd);
}
return dp[ix(0, P, 0)];
};
cout << (solve(H) - solve(H - 1) + M) % M << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。