比较经典且基础的区间dp,转移方程为
dp_max[i][j] = max(dp_max[i][j],dp_max[i][k] + dp_max[k+1][j] + sum[j]-sum[i-1]);
dp_min[i][j] = min(dp_min[i][j],dp_min[i][k] + dp_min[k+1][j] + sum[j]-sum[i-1]);
#include <fstream> #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; int main() { int n,a[150],sum[150]; int dp_max[150][150]; int dp_min[150][150]; while(~scanf("%d",&n)) { memset(dp_min,0x3f,sizeof(dp_min)); memset(dp_max,0,sizeof(dp_max)); sum[0] = 0; for(int i = 1;i <= n;i++) { dp_max[i][i] = dp_min[i][i] = 0; scanf("%d",&a[i]); sum[i] = sum[i-1] + a[i]; } for(int len = 1;len < n;len++) { for(int i = 1;i <= n-len;i++) { int j = i + len; for(int k = i;k < j;k++) { dp_max[i][j] = max(dp_max[i][j],dp_max[i][k] + dp_max[k+1][j] + sum[j]-sum[i-1]); dp_min[i][j] = min(dp_min[i][j],dp_min[i][k] + dp_min[k+1][j] + sum[j]-sum[i-1]); } } } printf("%d %d\n",dp_min[1][n],dp_max[1][n]); } return 0; }
时间: 2024-10-22 23:32:55