您的位置:首页 > 其它

DP(7)Post Office 1160

2013-04-28 20:56 435 查看
Post Office

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 13707 Accepted: 7376
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

Source
IOI 2000

在几个村庄中放上几个邮局,使得所有村庄到离他最近的邮局的距离总和最近。
看代码吧。。。
#include<stdio.h>
#include<string.h>
int d[305][310],P,V,v[310];//v[i]表示i的坐标。
long ans[35][310];//ans[i][j]表示在前j个村庄里放上i个邮局,需要的最短距离。
void distance()
{
memset(d,0,sizeof(d));
int i,j,k,mid;
for(i = 1;i<=V;i++)
{
for(j = i+1;j<=V;j++)
{
mid = (j+i)/2;
for(k = i;k<=j;k++)
d[i][j] += (v[k]-v[mid]>=0) ? (v[k]-v[mid]) : (v[mid]-v[k]);
//d[i][j]表示从i村庄到j村庄之间,只放一个邮局,最短的路程。
}
}
};
void min()
{
int i,j,k;
long tem;
memset(ans,0,sizeof(ans));
for(j = 1;j<=V;j++)
{
ans[1][j] = d[1][j];
}
for(i = 2;i<=P;i++)
for(j = i;j<=V;j++)
{
tem = 1000000;
for(k = 1;k<=j;k++)
{
if(tem > ans[i-1][k] + d[k+1][j])//dp问题,对k枚举,得到ans[i][j]
tem = ans[i-1][k] + d[k+1][j];
}
ans[i][j] = tem;
}//最后会得到ans[P][V];
};

int main()
{
while(scanf("%d %d",&V,&P)!=EOF)
{
memset(v,0,sizeof(v));
int i;
for(i=1;i<=V;i++)
scanf("%d",&v[i]);
distance();
min();
printf("%ld\n",ans[P][V]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM poj 动态规划 枚举