[IOI 2000]POJ 1160 Post Office

Post Office
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 22278   Accepted: 12034

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

 

【题意】

依次给定n个村庄在这条直线的位置,在n个村庄中建立p个邮局,求所有村庄到它最近的邮局的距离和,村庄在一条直线上,邮局建在村庄上。

 

【分析】 

首先求出在连续的几个村庄上建立一个邮局的最短距离,用数组dis[i][j]表示在第i个村庄和第j个村庄之间建一个邮局的最短距。

dis[i][j]=dis[i][j-1]+x[j]-x[(i+j)/2]; (村庄位置为x[i]

用数组dp[i][j]表示在前i个村庄中建立j个邮局的最小距离。即在前kk<i)个村庄建立j-1个邮局,在k+1j个村庄建立一个邮局。

dp[i][j]=min(dp[i][j],dp[k][j-1]+dis[k+1][i]) 

数据加强版点这里Accepted2016-03-26 

 

【代码】

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int N=305;
int n,p,x[N],dis[N][N],f[N][35];
inline void Init(){
	scanf("%d%d",&n,&p);
	for(int i=1;i<=n;i++) scanf("%d",&x[i]);
	for(int i=1;i<=n;i++){
		for(int j=i+1;j<=n;j++){
			dis[i][j]=dis[i][j-1]+x[j]-x[i+j>>1];
		}
	}
}
inline void Solve(){
	memset(f,0x3f,sizeof f);
	for(int i=1;i<=p;i++) f[i][i]=0;
	for(int i=1;i<=n;i++) f[i][1]=dis[1][i];
	for(int j=2;j<=p;j++){
		for(int i=j+1;i<=n;i++){
			for(int k=j-1;k<i;k++){
				f[i][j]=min(f[i][j],f[k][j-1]+dis[k+1][i]);
			}
		}
	}
	printf("%d\n",f[n][p]);
}
int main(){
	Init();
	Solve();
	return 0;
} 

 

 

posted @ 2019-02-23 10:22  神犇(shenben)  阅读(383)  评论(0编辑  收藏  举报