NC51244. 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; }