题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1227
借鉴链接:http://xuxiaoqi986.blog.163.com/blog/static/16737639820117344339350/
源代码:
#include<iostream>
#include<cmath>
using namespace std;
#include<string.h>
#define Min 0x7fffffff
int a[35][205];
int b[205];
int cost[205][205];
int main()
{
int n,k;
int i,j,l;
static int t=0;
while(cin>>n>>k)
{
t++;
if(n==0&&k==0) break;
for(i=1;i<=n;i++)
cin>>b[i];
memset(a,0,sizeof(a));
//对cost[i][j]进行初始化
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
{
cost[i][j]=0;
for(l=i;l<=j;l++)
cost[i][j]+=abs(b[l]-b[(i+j)/2]);
}
//dp初始化,当修1个仓库的时候
for(i=2;i<=n;i++)
a[1][i]=cost[1][i];
int min;
for(i=2;i<=k;i++)
for(j=2;j<=n;j++)
{
min=Min;
for(l=i;l<=j;l++)
if(a[i-1][l-1]+cost[l][j]<min) min=a[i-1][l-1]+cost[l][j];
a[i][j]=min;
}
cout<<"Chain "<<t<<endl;
cout<<"Total distance sum = ";
cout<<a[k][n]<<endl;
cout<<endl;
}
}