列表

详情


NC51244. Post Office

描述

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.

输入描述

Your program is to read from standard input. The first line contains two integers: the first is the number of villages V, , and the second is the number of post offices P, ,. 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 

输出描述

The first line contains one integer S, which is the sum of all distances between each village and its nearest post office.

示例1

输入:

10 5
1 2 3 6 7 9 11 22 44 50

输出:

9

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++ 解法, 执行用时: 8ms, 内存消耗: 5656K, 提交时间: 2021-11-13 10:56:14

#include<bits/stdc++.h>
using namespace std;
int a,b;
int dp[3010][301],dis[3010],sum[3010][3010],ty[3010][301];
int main(){
	scanf("%d%d",&a,&b);
	for(int i=1;i<=a;i++) scanf("%d",&dis[i]);
	sort(dis+1,dis+a+1);
	for(int i=1;i<=a;i++){
		for(int j=i+1;j<=a;j++){
			sum[i][j]=sum[i][j-1]+dis[j]-dis[(i+j)>>1];
		}
	}
	memset(dp,0x3f3f3f,sizeof(dp));
	dp[0][0]=0;
	for(int i=1;i<=b;i++){
        ty[a+1][i]=a;
		for(int j=a;j>=1;j--){
			for(int k=ty[j][i-1];k<=ty[j+1][i];k++){
				int ans=dp[k][i-1]+sum[k+1][j];
				if(ans<dp[j][i]) dp[j][i]=ans,ty[j][i]=k;
			}
		}
	}
	printf("%d",dp[a][b]);
	return 0;
}

上一题