山东省第二届ACM大学生程序设计竞赛 I - Sequence

      题目链接

Sequence

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

Given an integer number sequence A of length N (1<=N<=1000), we define f(i,j)=(A[i]+A[i+1]+...+A[j])^2 (i<=j). Now you can split the sequence into exactly M (1<=M<= N) succesive parts, and the cost of a part from A[i] to A[j] is f(i,j). The totle cost is the sum of the cost of each part. Please split the sequence with the minimal cost.

Input

At the first of the input comes an integer t indicates the number of cases to follow. Every case starts with a line containing N ans M. The following N lines are A[1], A[2]...A[N], respectively. 0<=A[i]<=100 for every 1<=i<=N.

Output

For each testcase, output one line containing an integer number denoting the minimal cost of splitting the sequence into exactly M succesive parts.

Sample Input

1
5 2
1 3 2 4 5

Sample Output

117

题意:n个数, 划分成连续的m段, 使每段和的平方的加和最小。

~~误入歧途了, 最开始觉得最小化最大值可解, 写完交了总是wa, 代码写的也没毛病, 但后来发现二分在某些数据的时候是得不到最优解的 = =。换个思路才恍然大悟是个dp。

前缀数组sum[i]记录前i个数的和, 用dp[i]递推划分前i个数的最优解。

看代码就懂了:

#include<bits/stdc++.h>
using namespace std;
long long sum[1005];
long long dp[1005];
long long min(long a, long b)
{
    return a > b ? b : a;
}
int main()
{
    int i, j, k, n, m, t;
    scanf("%d", &t);
    while(t--){
        sum[0] = 0;
        scanf("%d %d", &n, &m);
        for(i = 1;i <= n;i++){
            scanf("%lld", &sum[i]);
            sum[i] += sum[i - 1];//前缀数组
            dp[i] = sum[i] * sum[i];//划分数为1时dp[i]的最小值
        }
        for(i = 2;i <= m;i++)//i表示划分数, 从2划分开始递推到m划分
            for(j = n - m + i;j >= i;j--)//倒序递推, 确保dp数组不被更改   n - m + i为递推的有效起点, 之前的dp[]都不需要
                for(k = i - 1;k < j;k++)//遍历j之前的dp数组 计算结果得dp[j]的最小值
                    dp[j] = min(dp[j], dp[k] + (sum[j] - sum[k]) * (sum[j] - sum[k]));//递推式
        printf("%lld\n", dp[n]);
        memset(dp, 0, sizeof(dp));
        memset(sum, 0, sizeof(sum));
    }
    return 0;
}

~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值