Post Office
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 21315 | Accepted: 11522 |
Description
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.
Input
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.
Output
The first line contains one integer S, which is the sum of all distances between each village and its nearest post office.
Sample Input
10 5 1 2 3 6 7 9 11 22 44 50
Sample Output
9
题意:长度最大为300的数轴上有v个村庄和p个邮局, 邮局要建在村庄上, 求一种建立方案能使, 每个村庄到它最近的邮局的距离和最小, 输出最小和, 村庄升序输入。
题解:此题用动态规划思想解决, 递推的式子仔细想想不难想到, 用dp[i][j]表示前 i 个村庄设置 j 个邮局的距离最小值, 那么这个最小值可以由前 k 个村庄设置i - 1个邮局的最小值加上 k + 1个村庄到第 i 个村庄设置一个邮局的最小值得到, 所以有:dp[i][j] = min(dp[i][j], dp[k][j - 1] + sum[k + 1][i], k 就是分割点,通过枚举k的值就可以递推dp[i][j]数组。sum[i][j]表示从i 到 j 设置一个邮局的最小值, 对于任意多的一些村庄其设置邮局的最佳点总是在中间, 读者可以自己找样例计算一下, 当村庄为奇数个时, 最佳点在中间的村庄也就是起点 i 加上重点 j 再除以2, 偶数个时最佳点可以在中间两个随便取。化简一下素,
[i]j[j]数组也可以得到一个简单的递推公式:sum[i][j] = sum[i][j - 1] + a[j] - a[(i + j) / 2], 这样就可以得到任意i 到 j 的设置单个邮局的最短距离了。
AC代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int i, j, n, ans, v, p, x, k;
int dp[305][305], s[305], sum[305][305] = {0};
scanf("%d %d", &v, &p);
memset(dp, 0x3f, sizeof(dp));//初始化DP数组最大值
for(i = 1;i <= v;i++)
scanf("%d", &s[i]);
for(i = 1;i < v;i++)
for(j = i + 1;j <= v;j++)
sum[i][j] = sum[i][j - 1] + s[j] - s[(i + j) / 2];//计算sum数组
for(i = 1;i <= v;i++){
dp[i][i] = 0;//前i个村子 设置i个邮局是不需要花费的
dp[i][1] = sum[1][i];//前i 个村子设置一个邮局就是sum[1][i]
}
for(j = 2;j <= p;j++)
for(i = j + 1;i <= v;i++)
for(k = j - 1;k < i;k++)
dp[i][j] = min(dp[i][j], dp[k][j - 1] + sum[k + 1][i]);//状态转移
printf("%d\n", dp[v][p]);
return 0;
}
嘿嘿~有帮助的话就麻烦点个赞, 蟹蟹~~~