标签:
Sequence
Time Limit: 1000ms Memory limit: 65536K
题目描述
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.
输入
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.
输出
For each testcase, output one line containing an integer number denoting the minimal cost of splitting the sequence into exactly M succesive parts.
示例输入
1
5 2
1 3 2 4 5
示例输出
117
将区间分为m段,使得m段的平方和最小。
我们定义一个Dp数组Dp[i][j]表示以i结尾,分为j段的最小和,那么对于区间[L+1,i],Dp[i][j] = min(Dp[i][j],Dp[L][j-1]+∑k=L+1ia[k] )
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long LL;
const int Max = 1100;
const int INF = 0x3f3f3f3f;
int a[Max];
LL sum[Max];
LL Dp[Max][Max];
int main()
{
int T;
int n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&n,&m);
sum[0] = 0;
for(int i = 1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i] = sum[i-1]+a[i];
}
for(int i = 1;i<=n;i++)
{
Dp[i][1] =sum[i]*sum[i];
for(int j = max(m-n+i,2);j<=i;j++)
{
Dp[i][j] = INF;
if(j>m)//剪枝
{
break;
}
for(int k = i-1;k>=j-1;k--)
{
Dp[i][j] = min(Dp[i][j],Dp[k][j-1]+(sum[i]-sum[k])*(sum[i]-sum[k]));
if((sum[i]-sum[k])*(sum[i]-sum[k])>=Dp[i][j])//不必要进行的部分
{
break;
}
}
}
}
printf("%lld\n",Dp[n][m]);
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/huayunhualuo/article/details/51333778