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
动态规划问题
思路:把每一位置对应的从1到该位置截取i段的最优解求出,i从1循环到M。
#include<iostream> #include<string.h> using namespace std; int main() { long int dp[1001]; long int f[1001];//记录输入 long int t,m,n,i,j,x,sum,max; cin>>t; while(t--) { cin>>n>>m; for(i=1;i<=n;i++) cin>>f[i]; sum=0; memset(dp,0,sizeof(dp)); for(i=1;i<=n-(m-1);i++)//1-n取一串的情况 { sum+=f[i]; dp[i]=sum*sum; } max=dp[i-1]; for(i=2;i<=m;i++)//求截取2-n串的情况 { max=1000000000; for(x=n-(m-i);x>=i;x--)//每个位置的最优解 { sum=0; for(j=x;j>=i;j--) { sum+=f[j]; if(j==x) dp[x]=dp[j-1]+sum*sum; else if(dp[x]>dp[j-1]+sum*sum) dp[x]=dp[j-1]+sum*sum;//dp方程 } if(x==n&&max>dp[x]) max=dp[x]; } } cout<<max<<endl; } return 0; }