以下程序应用动态规划进行优化
#include <stdio.h>
#include<stdlib.h>
#include <assert.h>
#include <string.h>
int lineSave[100][100];
int main(void)
{//fun
int n ;
int k ;
int i,j,v ;
int blockLen,blockNumber;
int sum,weight,index;
int *data;
int getRangeWeight(int *data,int start,int end);
scanf("%d%d", &n, &k);
assert(n >= k);
data=(int*)malloc(n*4);
blockLen=k+2;
blockNumber=n-k+1;
for (i = 0; i < n; ++i)
scanf("%d", data+i);
for(i=0;i<k;++i)
lineSave[0][i]=i;
lineSave[0][k]=n;
lineSave[0][k+1]=0;
for(i=1;i<blockNumber;i++)
memcpy(&lineSave[i][0],lineSave,blockLen*4);
for(i=k-1;i>0;--i)
{//for01
for(j=0;j<blockNumber;++j)
{//for02
lineSave[j][i]+=j;
lineSave[j][blockLen-1]+=getRangeWeight(data,lineSave[j][i],lineSave[j][i+1]);
for(v=j+1;v<blockNumber;++v)
{//for03
if((weight=lineSave[v][blockLen-1]+getRangeWeight(data,lineSave[j][i],lineSave[v][i+1]))<lineSave[j][blockLen-1])
{
lineSave[j][blockLen-1]=weight;
memcpy(&lineSave[j][i+1],&lineSave[v][i+1],(k-i-1)*4);
}
}//for03
}//for02
}//for01
weight=0x7fffffff;
for(i=0;i<blockNumber-1;++i)
{
int w;
w=getRangeWeight(data,0,lineSave[i][1])+lineSave[i][k+1];
if(w<weight)
{
weight=w;
index=i;
}
}
sum=weight*2;
for(i=0;i<n;++i)
sum+=data[i]*data[i];
printf("%d\n",sum);
j=0;
printf("%d",data[0]);
++j;
for(i=1;i<k;++i)
{//for01
for(;j<lineSave[index][i];++j)
printf(" %d",data[j]);
printf("|%d",data[j]);
++j;
}//for01
for(;j<lineSave[index][k];++j)
printf(" %d",data[j]);
printf("\n");
free(data);
return 0;
}//fun
int getRangeWeight(int *data,int start,int end)
{
int weight=0,i,j;
if(end-start<=1) return 0;
for(i=start;i<end-1;++i)
for(j=i+1;j<end;++j)
weight+=data[i]*data[j];
return weight;
}