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;
}
~~~