hdu 2829

稍微比划一下,可以知道cost[i][j]满足四边形不等式的规则

#include <cstdio>
#include <cstring>
const int MAXN = 1000 + 123;
int dp[MAXN][MAXN], cost[MAXN][MAXN], s[MAXN][MAXN];
int a[MAXN], sum[MAXN];
int main()
{
    int n, m ;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        if(n == 0 && m == 0)  break;
        sum[0] = 0;
        for(int i = 1; i  <= n; i++)
        {
            scanf("%d", &a[i]);
            sum[i] = sum[i-1] + a[i];
        }

        memset(cost, 0, sizeof(cost));
        for(int i = 1; i <= n; i++)
          for(int j = i + 1; j <= n; j++)
             cost[i][j] = cost[i][j-1] + (sum[j-1] - sum[i-1]) * a[j];

        for(int i = 1; i <= n; i++)
        {
            s[i][0] = 0;
            dp[i][0] = cost[1][i];
        }

        for(int k = 1; k <= m; k++)
        {
            s[n+1][k] = n - 1;
            for(int i = n; i >= k + 1; i--)
            {
                dp[i][k] = dp[k][k-1] + cost[k+1][i];
                s[i][k] = k;
                for(int j = s[i][k-1]; j <= s[i+1][k]; j++)
                {
                    if(dp[j][k-1] + cost[j+1][i] < dp[i][k])
                    {
                        dp[i][k] = dp[j][k-1] + cost[j+1][i];
                        s[i][k] = j;
                    }
                }
            }
        }

        printf("%d\n",dp[n][m]);
    }
    return 0;
}


你可能感兴趣的:(hdu 2829)