![](http://acm.fzu.edu.cn/image/problem.gif)
Accept: 730 Submit: 2020
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
The fastfood chain McBurger owns several restaurants along a highway. Recently, they have decided to build several depots along the highway, each one located at a restaurant and supplying several of the restaurants with the needed ingredients. Naturally, these depots should be placed so that the average distance between a restaurant and its assigned depot is minimized. You are to write a program that computes the optimal positions and assignments of the depots.
To make this more precise, the management of McBurger has issued the following specification: You will be given the positions of n restaurants along the highway as n integers d1 < d2 < ... < dn (these are the distances measured from the company's headquarter, which happens to be at the same highway). Furthermore, a number k (k <= n) will be given, the number of depots to be built.
The k depots will be built at the locations of k different restaurants. Each restaurant will be assigned to the closest depot, from which it will then receive its supplies. To minimize shipping costs, the total distance sum, defined as
![](http://acm.fzu.edu.cn/image/Problem/1005.gif)
must be as small as possible.
Write a program that computes the positions of the k depots, such that the total distance sum is minimized.
Input
The input file will end with a case starting with n = k = 0. This case should not be processed.
Output
Output a blank line after each test case.
Sample Input
Sample Output
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int m[205][205],dis[205],w[205][205];
int main(){
int count=1;
int n,k;
while(cin>>n>>k){
if(n==0&&k==0)
return 0;
memset(dis,0,sizeof(dis));
memset(m,0,sizeof(m));
for(int i=1;i<=n;i++)
cin>>dis[i];
for(int i=1;i<=n;i++){
m[i][i]=0;
for(int j=i+1;j<=n;j++){
m[i][j]=m[i][j-1]+dis[j]-dis[(i+j)/2];
}
}
for(int j=1;j<=n;j++)
w[1][j]=m[1][j];
for(int r=2;r<=k;r++){
w[r][r]=0;
for(int i=r+1;i<=n;i++){
w[r][i]=10000000;
for(int j=r-1;j<i;j++){
int temp=w[r-1][j]+m[j+1][i];
if(temp<w[r][i])
w[r][i]=temp;
}
}
}
cout<<"Chain "<<count++<<endl;
cout<<"Total distance sum = "<<w[k][n]<<endl<<endl;
}
return 0;
}