POJ 1160 Post Office

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

分析:两个地方之间,当邮局建在中间的位置处,距离和最小,

状态转移方程  dis[i][j]=min(dis[i][j],dis[k][j-1]+sum[k+1][j])  dis[i][j] 表示前i个村庄建立j个邮局的最小距离。

code:

View Code
#include<stdio.h>
#include<string.h>
#define min(a,b)(a)<(b)?(a):(b)
#define clr(x)memset(x,0,sizeof(x))
int abs(int x)
{
if(x<0)
return -1*x;
return x;
}
int a[303];
int dis[303][303];
int sum[303][303];
int main()
{
int i,j,k,n,m,mid;
while(scanf("%d%d",&n,&m)!=EOF)
{
clr(a);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
sum[i][j]=0;
mid=(i+j)>>1;
for(k=i;k<=j;k++)
sum[i][j]+=abs(a[k]-a[mid]);
}

memset(dis,0x7f,sizeof(dis));
for(i=0;i<n;i++)
dis[i][1]=sum[0][i];
for(i=2;i<=m;i++)
for(j=i;j<n;j++)
for(k=i;k<j;k++)
dis[j][i]=min(dis[j][i],dis[k][i-1]+sum[k+1][j]);
printf("%d\n",dis[n-1][m]);
}
return 0;
}


posted @ 2012-03-14 18:10  'wind  阅读(340)  评论(0编辑  收藏  举报