Input
The input file contains several descriptions of fastfood chains. Each description starts with a line containing the two integers n and k. n and k will satisfy 1 <= n <= 200, 1 <= k <= 30, k <= n. Following this will n lines containing one integer each, giving the positions di of the restaurants, ordered increasingly.
The input file will end with a case starting with n = k = 0. This case should not be processed.
Output
For each chain, first output the number of the chain. Then output a line containing the total distance sum.
Output a blank line after each test case.
Sample Input
6 3
5
6
12
19
20
27
0 0
Sample Output
Chain 1
Total distance sum = 8
- dp[i][j]表示是前j个饭店有i个仓库的情况
- 转移方程就是
- dp[i][j]=min(dp[i][j],dp[i-1][h]+dis[h+1][j]);
- 其中 h>=i-1 (存在i-1个仓库至少有i-1个饭店)h<=j-1 (j这个饭店在这个次才加入作为仓库,所以不能取)
- 其中dis[h+1][j]表示在h+1-j编号中选择一家饭店做仓库 且h+1 -j都已该仓库为中心 新增的距离
- 由于货仓选址已知应该选择编号最中间的点为仓库(编号为中位数的那个数)
LINK
#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int d[210],dis[210][210],dp[210][210];
int main()
{
int n,k,cas=0;while(~scanf("%d%d",&n,&k))
{
if(n==0&&k==0) return 0;
for(int i=1;i<=n;i++) scanf("%d",&d[i]);
for(int i=1;i<=n-1;i++)
{
for(int j=i;j<=n;j++)
{
int mid=(i+j)/2;dis[i][j]=0;
for(int h=i;h<=j;h++)
{
dis[i][j]+=abs(d[h]-d[mid]);
}
}
}
for(int i=1;i<=k;i++) for(int j=1;j<=n;j++) dp[i][j]=inf;
for(int i=1;i<=n;i++ ) dp[1][i]=dis[1][i];
for(int i=2;i<=k;i++)
{
for(int j=1;j<=n;j++)
{
for(int h=i-1;h<=j-1;h++)
{
dp[i][j]=min(dp[i][j],dp[i-1][h]+dis[h+1][j]);
}
}
}
printf("Chain %d\n",++cas);
printf("Total distance sum = %d\n\n",dp[k][n]);
}
}