您的位置:首页 > 其它

FOJ-1005 Fast Food

2017-12-27 23:41 288 查看
http://acm.fzu.edu.cn/problem.php?pid=1005

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.

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



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 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]: 前i个快餐店中有j个作为仓库选址时,各快餐店与其最近的仓库的距离之和的最小值。

dis[i][j]: 快餐店i到j之间只有一个仓库时,i到j之间的所有快餐店与该仓库的距离之和的最小值。

(取(i + j)/ 2作为仓库时得到最小值)

dp[i][j] =

min

{

dp[i][j],

dp[i-1][j-1]+dis[i][i],

dp[i-2][j-1]+dis[i-1][i],

… ,

dp[j-1][j-1]+dis[j][i]

}

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int cnt, n, k, d[205], dp[205][35], dis[205][205];
int main()
{
while (scanf("%d%d", &n, &k), n, k)
{
memset(dp, 0x3f, sizeof dp);
memset(dis, 0, sizeof dis);
for (int i = 1; i <= n; i++)
scanf("%d", &d[i]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
for (int k = i; k <= j; k++)
dis[i][j] += abs(d[k] - d[(i + j) / 2]), dp[i][1] = dis[1][i];
for (int j = 2; j <= k; j++)
for (int i = j; i <= n; i++)
if (i == j)
dp[i][j] = 0;
else for (int k = j - 1; k <= i; k++)
dp[i][j] = min(dp[i][j], dp[k][j - 1] + dis[k + 1][i]);
printf("Chain %d\nTotal distance sum = %d\n\n", ++cnt, dp
[k]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: