题解 | #【模板】区间dp#
【模板】区间dp
https://www.nowcoder.com/practice/f482a7ca9257422dbd7bd495d9d04f7a
区间dp模板
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 705; int __t = 1, n, a[N], sum[N], dp[N][N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; sum[i] = sum[i - 1] + a[i]; } memset(dp, 0x3f, sizeof(dp)); for (int i = 1; i <= n; i++) { dp[i][i] = 0; } for (int len = 2; len <= n; len++) { for (int i = 1; i + len - 1 <= n; i++) { int j = i + len - 1; for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum[j] - sum[i - 1]); } } } cout << dp[1][n] << "\n"; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }