// 经典DP +货仓选址 Fast Food hdu1227

22 篇文章 0 订阅

在这里插入图片描述
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]);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值