HihoCoder 1636 Pangu and Stones(区间DP)题解

时间:2022-04-09 04:44:25

题意:合并石子,每次只能合并l~r堆成1堆,代价是新石堆石子个数,问最后能不能合成1堆,不能输出0,能输出最小代价

思路:dp[l][r][t]表示把l到r的石堆合并成t需要的最小代价。

当t == 1时,dp[i][j][1] = min(dp[i][j][1], dp[i][k][t] + dp[k + 1][j][1] + sum[j] - sum[i - 1]),其中t属于[l - 1, r - 1]

当t >= 2时,dp[i][j][t] = min(dp[i][j][t], dp[i][k][t - 1] + dp[k + 1][j][1])。

初始化:

for(int i = ; i <= n; i++){
for(int j = i; j <= n; j++){
dp[i][j][j - i + ] = ;
}
}

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
const int maxn = + ;
const int MOD = 1e9 + ;
const int INF = 0x3f3f3f3f;
int a[maxn], dp[maxn][maxn][maxn], sum[maxn];
int main(){
int n, l, r;
while(~scanf("%d%d%d", &n, &l, &r)){
sum[] = ;
for(int i = ; i <= n; i++){
scanf("%d", &a[i]);
sum[i] = a[i] + sum[i - ];
}
memset(dp, INF, sizeof(dp));
for(int i = ; i <= n; i++){
for(int j = i; j <= n; j++){
dp[i][j][j - i + ] = ;
}
}
for(int len = ; len <= n; len++){
for(int i = ; i + len - <= n; i++){ int j = i + len - ;
for(int k = i; k < j; k++){
for(int t = l - ; t <= r - ; t++){
dp[i][j][] = min(dp[i][j][], dp[i][k][t] + dp[k + ][j][] + sum[j] - sum[i - ]);
}
} for(int t = ; t <= len; t++){
for(int k = i; k < j; k++){
dp[i][j][t] = min(dp[i][j][t], dp[i][k][t - ] + dp[k + ][j][]);
}
} }
} if(dp[][n][] >= INF) printf("0\n");
else printf("%d\n", dp[][n][]);
}
return ;
}