Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 15464 | Accepted: 8378 |
Description
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
Output
Sample Input
10 5 1 2 3 6 7 9 11 22 44 50
Sample Output
9
Source
#include<stdio.h>
#include<string.h>
int sum[305][305];//第i个村庄到第j个村建一个邮局的距离
int dp[305][35];//在i个村子造j个邮局的代价
int dis[305];
int min(int a,int b)
{
return a<b?a:b;
}
int main()
{
int v,p;
while(~scanf("%d%d",&v,&p))
{
for(int i=1;i<=v;i++)
scanf("%d",&dis[i]);
memset(sum,0,sizeof(sum));
memset(dp,0,sizeof(dp));
for(int i=1;i<=v;i++)
for(int j=i+1;j<=v;j++)
sum[i][j]=sum[i][j-1]+dis[j]-dis[(i+j)>>1];
for(int i=1;i<=v;i++)
dp[i][1]=sum[1][i];//显然在i个村庄造1个的话,相当于sum[1][i]
for(int j=2;j<=p;j++)//注意循环的位置,建立j个邮局,至少j个村庄,所以村庄受邮局限制
{
for(int i=j+1;i<=v;i++)
{
dp[i][j]=0x3f3f3f;
for(int 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;
}