您的位置:首页 > 其它

POJ 1160Post Office【DP】

2012-07-31 13:36 387 查看
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

Post Office

题意:在V个村庄上建立P个邮局,使每个村庄到达邮局的最小距离最小。

思路:dp[i][j]表示前i个村庄,建立j个邮局,sum[i][j]表示i, j之间建立1个邮局的最小距离和,sum[i][j]=sum[i][j-1]+p[j]-p[(i+j)/2];//HRBUST 有一利用此公式的题目

样例解析: 1 2 3 6 7 9 11 22 44 50

建1 建2 建3 建4 建5

状态转移方程为:dp[i][j]=min(dp[i][j], dp[k][j-1]+sum[k+1][i]);

代码如下:

#include<string.h>
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int i, j, k, v, p;
int sum[302][302], pp[302], dp[302][32];
while(scanf("%d%d", &v, &p)!=EOF)
{
memset(sum, 0, sizeof(sum));
memset(pp, 0, sizeof(pp));
memset(dp, 0, sizeof(dp));
for(i=1; i<=v; i++)
scanf("%d", &pp[i]);
for(i=1; i<=v; i++)
{
for(j=i; j<=v; j++)
sum[i][j]=sum[i][j-1]+pp[j]-pp[(i+j)/2];
}
for(i=1; i<=v; i++)
dp[i][1]=sum[1][i];
for(j=2; j<=p; j++)
for(i=1; i<=v; i++)
{
int minnum=0xfffffff;
for(k=j-1; k<i; k++)
{
minnum=min(minnum, dp[k][j-1]+sum[k+1][i]);
}
dp[i][j]=minnum;
}
printf("%d\n", dp[v][p]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: