描述
There is a straight highway with villages alongside the highway. The highway is represented as an integer axis, and the position of each village is identified with a single integer coordinate. There are no two villages in the same position. The distance between two positions is the absolute value of the difference of their integer coordinates.
Post offices will be built in some, but not necessarily all of the villages. A village and the post office in it have the same position. For building the post offices, their positions should be chosen so that the total sum of all distances between each village and its nearest post office is minimum.
You are to write a program which, given the positions of the villages and the number of post offices, computes the least possible sum of all distances between each village and its nearest post office.
输入
Your program is to read from standard input. The first line contains two integers: the first is the number of villages V, 1 <= V <= 300, and the second is the number of post offices P, 1 <= P <= 30, P <= V. The second line contains V integers in increasing order. These V integers are the positions of the villages. For each position X it holds that 1 <= X <= 10000.
输出
The first line contains one integer S, which is the sum of all distances between each village and its nearest post office.
样例输入
10 5
1 2 3 6 7 9 11 22 44 50
样例输出
9
解题思路https://blog.csdn.net/Wanglinlin_bfcx/article/details/78005881:
这题用的是动态规划的解题思路,但是这题的状态转移方程不是太好找;
f[i][j]:表示从i个村庄中选取j个作为邮局的路径综合的最小值
mi[i][j]:表示从第i个村庄到第j个村庄的只建立一个邮局的路径的最小值;
可以很明显的得出若从第i个村庄到第j个村庄只选取一个作为邮局的话则选择第(i+j)/2个,2、下面考虑建立多个邮局的问题,可以这样将该问题拆分为若干子问题,在前i个村庄中建立j个邮局的最短距离,是在前k个村庄中建立j-1个邮局的最短距离与 在k+1到第i个邮局建立一个邮局的最短距离的和。而建立一个邮局我们在上面已经求出,则动态转移方程可得f[i][j]=min(f[i][j],f[k][j-1]+mi[k+1][j])
其中状态边界f[i][1]=mi[1][i];mi[i][j]=mi[i][j-1]+a[i]-a[(i+j)/2];
代码
#include<bits/stdc++.h>
using namespace std;
int v[1005];
int dp[505][505];//i个村庄中j个邮局
int pd[505][505];//第i个村庄到第j个村庄只有一个邮局的最小费用。
int main(){
int n,m;
cin>>n>>m;
memset(dp,0x1f,sizeof(dp));
for(int i=1;i<=n;i++){
cin>>v[i];
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
pd[i][j]=pd[i][j-1]+v[j]-v[(i+j)/2];
}
dp[i][1]=pd[1][i];
}
for(int i=2;i<=n;i++){
for(int j=2;j<=m;j++){
for(int k=j-1;k<i;k++)
dp[i][j]=min(dp[i][j],dp[k][j-1]+pd[k+1][i]);
}
}
cout << dp[n][m] <<endl;
return 0;
}
本文介绍了一种利用动态规划解决邮局选址问题的方法,旨在最小化所有村庄到最近邮局的距离总和。通过定义状态转移方程,文章详细解释了如何从i个村庄中选择j个作为邮局,以达到路径综合最小值。代码实现部分展示了如何使用C++进行编程,包括初始化状态矩阵、计算单邮局情况下的最小费用及多邮局情况下的最优解。
1243

被折叠的 条评论
为什么被折叠?



