The distance and minimum number of N numbers to a number must be their median.
DP [I] [J] = the distance between the first I points and the J offices.
DP [I] [J] = min (DP [k-1] [J-1] + W [k] [I]) W [k] [I] is k .. i.
Post Office
Time limit:1000 ms |
|
Memory limit:10000 K |
Total submissions:15687 |
|
Accepted:8503 |
Description There is a straight highway with ages 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 ages 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 ages. A village and the post office in it have the same position. for building the post offices, their positions shocould 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 versions 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 ages 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 ages. 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 51 2 3 6 7 9 11 22 44 50 Sample output 9 Source IOI 2000 |
[Submit] [Go Back] [Status] [discuss]
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn=500;const int INF=0x3f3f3f3f;int dp[maxn][maxn/10],w[maxn][maxn];int n,m,a[maxn];int main(){while(scanf("%d%d",&n,&m)!=EOF){for(int i=1;i<=n;i++){scanf("%d",a+i);}memset(w,63,sizeof(w));for(int i=1;i<=n;i++){for(int j=i;j<=n;j++){int mid=(i+j)/2,temp=0;for(int k=i;k<=j;k++){temp+=abs(a[k]-a[mid]);}w[i][j]=temp;}}memset(dp,63,sizeof(dp));for(int i=1;i<=n;i++){dp[i][1]=w[1][i];}for(int i=2;i<=n;i++){for(int j=2;j<=m;j++){if(j>=i){dp[i][j]=0;continue;}for(int k=1;k<i;k++){dp[i][j]=min(dp[i][j],dp[k][j-1]+w[k+1][i]);}}}printf("%d\n",dp[n][m]);}return 0;}