//MADE BY Y_is_sunshine;
//#include <bits/stdc++.h>
//#include <memory.h>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define INF 0x3f3f3f3f
#define MAXN 2005
const int mod = 1e9 + 7;
const double PI = acos(-1);
using namespace std;
int N, M;
int T;
int dp[MAXN][MAXN];
int d[MAXN];
int sum[MAXN];
int s[MAXN][MAXN];
int main()
{
freopen("data.txt", "r", stdin);
while (cin >> N) {
memset(dp, 0x3f, sizeof(dp));
memset(s, 0, sizeof(s));
for (int i = 1; i <= N; i++)
scanf("%d", &d[i]), sum[i] = sum[i - 1] + d[i], s[i][i] = i;
for (int i = 1; i <= N; i++)
d[i + N] = d[i], sum[i + N] = sum[i + N - 1] + d[i], s[i + N][i + N] = i + N;
for (int len = 1; len <= N; len++) {
for (int i = 1; i + len <= 2 * N; i++) {
dp[i][i] = 0;
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]);
for (int k = s[i][j - 1]; k <= s[i + 1][j]; k++) {
if (dp[i][k] + dp[k + 1][j] + sum[j] - sum[i - 1] < dp[i][j]) {
dp[i][j] = dp[i][k] + dp[k + 1][j] + sum[j] - sum[i - 1];
s[i][j] = k;
}
}
}
}
int ans = INF;
for (int i = 1; i <= N; i++)
ans = min(ans, dp[i][i + N - 1]);
printf("%d\n", ans);
}
freopen("CON", "r", stdin);
system("pause");
return 0;
}
区间DP 环形石子问题 四边形优化
最新推荐文章于 2021-03-12 12:08:16 发布