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
这题是区间dp经典,看了别人的代码,自己写出来了。可以先设两个数组sum[i][j]和dp[i][j],sum[i][j]表示第i和第j个村庄之间建一个邮局并且这些村庄的花费都和这个邮局计算得到的最小花费,dp[i][j]表示前i个村庄中间j个邮局并且这i个村庄的花费计算都与这些邮局有关的最小花费。
那么前i个村庄中建j个邮局的最小花费可以由前k个村庄中建i-1个邮局的最小花费加上第k个邮局到第i个邮局建一个邮局的最小花费转移过来,即dp[i][j]=min(dp[i][j],dp[k][j-1]+sum[k+1][i]);
这里的初始条件是dp[i][1]=sum[1][i].
当邮局数为1时,我们把邮局建在中间就行了,当邮局有多个时,就有sum[i][j]=sum[i][j-1]+pos[j]-pos[(i+j)/2]。
#include<stdio.h> #include<string.h> #define maxn 350 #define inf 88888888 int min(int a,int b){ return a<b?a:b; } int pos[maxn],sum[maxn][maxn],dp[maxn][35]; int main() { int n,m,i,j,k; while(scanf("%d%d",&n,&m)!=EOF) { memset(dp,inf,sizeof(dp)); memset(sum,0,sizeof(sum)); for(i=1;i<=n;i++){ scanf("%d",&pos[i]); } if(n==m){ printf("0\n");continue; } for(i=1;i<=n-1;i++){ for(j=i+1;j<=n;j++){ sum[i][j]=sum[i][j-1]+pos[j]-pos[(i+j)/2]; } } for(i=1;i<=n;i++){ dp[i][1]=sum[1][i]; } for(j=2;j<=m;j++){ for(i=j+1;i<=n;i++){ for(k=1;k<=i;k++){ dp[i][j]=min(dp[i][j],dp[k][j-1]+sum[k+1][i]); } } } printf("%d\n",dp[n][m]); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。