Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9376 | Accepted: 5027 |
Description
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
Output
Sample Input
10 5 1 2 3 6 7 9 11 22 44 50
Sample Output
9
Source
/*
假设cost[v][p]表示1-v号村庄一共设置p个邮局所可以得到的最短距离
那么可以对最后一个邮局进行DP
DP方程(从中间分成两个最优子问题) cost[vNum][pNum] = min{cost[range][p - 1] + sin[range + 1][vNum]
1)cost[range][p - 1]表示前p-1个邮局可以最优覆盖1-range个村庄, range范围是[pNum - 1, vNum - 1]
因为pNum - 1邮局至少可以去最优覆盖pNum - 1个邮局
2)sin[range + 1][vNum]表示第pNum个邮局可以最优覆盖range + 1致第vNum个村庄的最优距离
3)cost[vNum][pNum]只与cost[...][pNum - 1]有关,所有一MAX_N * 2数组即可搞定(空间压缩)
*/
#include <iostream>
#define MAX_N 305
using namespace std;
int vNum, pNum, minCost = INT_MAX;
int dist[MAX_N + 1];
int sinD[MAX_N + 1][MAX_N + 1]; //sinD[a, b]表示在a村庄和b村庄之间建立一个邮局可以得到的最短总距离
int cost[MAX_N + 1][2];
void initial()
{
int i, j;
memset(sinD, 0, sizeof(sinD));
for(i = 1; i <= vNum; i++)
{
for(j = i + 1; j <= vNum; j++)
sinD[i][j] = sinD[i][j - 1] + dist[j] - dist[int((i + j) / 2)];
//初始化
//cost[i][0]相当于分析中的cost[i][1],只不过这里用第二维数组用2取代pNum进行了空间压缩
cost[i][0] = sinD[1][i];
}
}
void input()
{
cin>>vNum>>pNum;
for(int i = 1; i <= vNum; i++)
cin>>dist[i];
}
void dpSolve()
{
int last = 0, cur = 1;
//从邮局数量开始初始邮局数量等于1已经在initial中算过了,所以这里仅从2开始
for(int pn = 2; pn <= pNum; pn++)
{
cur = 1 - last;
//村庄数量至少等于邮局数量,否则最优结果肯定为0,是不需要考虑的
for(int vn = pn; vn <= vNum; vn++)
{
int curMin = INT_MAX;
//前pn - 1个邮局可以覆盖的村庄范围
for(int range = pn - 1; range <= vn - 1; range++)
{
int curDist = cost[range][last] + sinD[range + 1][vn];
if(curDist < curMin) curMin = curDist;
}
cost[vn][cur] = curMin;
}
last = cur;
}
if(pNum <= 1) cur = 0;
cout<<cost[vNum][cur]<<endl;
}
int main()
{
input();
initial();
dpSolve();
return 0;
}