ProgramAlgTrain/20240919/CSP常考算法模板/区间dp/区间dp_合并石子.cpp

57 lines
1014 B
C++
Raw Permalink Normal View History

2024-09-19 02:22:41 +00:00
#include <bits/stdc++.h>
using namespace std;
int a[101];
int sum[101]; // prefix sum
int f[101][101];
/*
2024-09-19 03:25:26 +00:00
2024-09-19 03:11:59 +00:00
2024-09-19 03:25:26 +00:00
1.dp[i][j]
1n堆石子合成一堆
dp[i][j]i堆到第j堆石子合成一堆
2.dp[i][j]
i-j之间选一个中间值k
dp[i][j] = dp[i][k] + dp[k+1][j] + ( sum[j] - s[i-1] );
3.dp[0][0],dp[0][j],dp[i][0],dp[i][j],dp[i][i]
2024-09-19 02:22:41 +00:00
*/
/*
input
7
13
7
8
16
21
4
18
output
239
*/
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
for(int i=1; i<=n; i++) {
cin>>a[i];
sum[i] = sum[i-1] + a[i];
}
2024-09-19 03:11:59 +00:00
for(int i=n-1; i>=1; i--) { //一定要逆序
2024-09-19 02:22:41 +00:00
for(int j=i+1; j<=n; j++) {
f[i][j] = INT_MAX;
for(int k=i; k<=j-1; k++) {
f[i][j] = min(f[i][j], f[i][k]+f[k+1][j] + sum[j]-sum[i-1]);
}
}
}
cout<<f[1][n]<<endl;
return 0;
}