hit 2952 //石子归并 的 平行四边形不等式解法

与前面的几个四边形不等式稍微有些不同,但是还是比较容易证明出满足四边形不等式规则的

接着注意一下初始化



#include <cstdio>
#include <cstring>
const int MAXN = 1010 * 2;
const int inf = 1 << 29;
int a[MAXN];
int sum[MAXN];
int dp[MAXN][MAXN], s[MAXN][MAXN];
int main()
{
    int n;
    while(scanf("%d", &n) != EOF)
    {
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
            a[i + n] = a[i];
        }

        sum[0] = 0;
        for(int i = 1; i <= 2 * n; i++)
        {
            sum[i] = sum[i-1] + a[i];
        }

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

        for(int k = 1; k < n; k++)
        {
            s[2*n-k+1][k] = 2 * n - 1;
            for(int i = 2 * n - k; i >= 0; i--)
            {
                dp[i][i+k] = inf;
                for(int j = s[i][k-1]; j <= s[i+1][k]; j++)
                {
                    int temp = dp[i][j] + dp[j+1][i+k] + sum[i+k] - sum[i-1];
                    //printf("i=%d j=%d i+k=%d %d\n",i,j,i+k,temp);
                    if(temp < dp[i][i+k])
                    {
                        dp[i][i+k] = temp;
                        s[i][k] = j;
                    }
                }
                //printf("dp[%d][%d]=%d\n",i,i+k,dp[i][i+k]);
            }
        }

        int ans = inf;
        for(int i = 1; i <= n; i++)
        if(dp[i][i+n-1] < ans)  ans = dp[i][i+n-1];
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(hit 2952 //石子归并 的 平行四边形不等式解法)