POJ P1160 Post Office
题目
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
题目大意
给出n个村庄,m个邮局,求出在最优建邮局的方案下,所有村庄离最近的邮局的距离和
题解
DP+贪心
f[i][j]表示前i个村庄建了j个邮局的最小值
f[i][j]=min(f[i][j],f[i-1][k]+sum[k+1][i]) (sum[k+1][i]表示在k+1和i之间的村庄里建一个邮局的最小距离和)
在构造sum的时候我们会想到一个贪心:当在某个最优的建邮局的方案中,设建邮局的村庄的左边的个数为x,右边的个数为y,那么,当再往这个块的最右边加入一个村庄时,很显然,建邮局的地方会往右移1个位置或者不动,如果往右移,那么左边的村庄都要再加上d,总增量为x*d,右边的村庄的距离都要减少d,总减量为y*d,很显然当且仅当左右两边的村庄数相差1或相等时,这个方案为最优建邮局方案
自己不太会证明……有点说不清楚这个贪心的思想……
代码未交过,因为POJ在维护中……
代码
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int n,m;
int x[305],f[305][35],sum[305][305];
int readln()
{
int x=0;
char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while ('0'<=ch&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
int min(int x,int y){return x<y?x:y;}
void qsort(int l,int r)
{
int i=l,j=r,mid=x[rand()%(r-l+1)+l],t;
do {
while (x[i]<mid) i++;
while (x[j]>mid) j--;
if (i<=j) {
t=x[i];x[i]=x[j];x[j]=t;
i++;j--;
}
}while (i<=j);
if (i<r) qsort(i,r);
if (l<j) qsort(l,j);
}
int find(int a,int b,int c)
{
int l=a,r=b,mid;
while (l<=r)
{
mid=(l+r)>>1;
if (2*x[mid]<c) l=mid+1;else r=mid-1;
}
return l;
}
int main()
{
memset(f,63,sizeof(f));
while (~scanf("%d%d",&n,&m))
{
for (int i=1;i<=n;i++) x[i]=readln();
qsort(1,n);
for (int i=1;i<=n;i++)
for (int j=i;j<=n;j++)
sum[i][j]=sum[i][j-1]+x[j]-x[(i+j)/2];
f[0][0]=0;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
for (int k=0;k<i;k++)
f[i][j]=min(f[i][j],f[k][j-1]+sum[k+1][i]);
printf("%d\n",f[n][m]);
}
return 0;
}