POJ1160 Post Office[序列DP]

Candy?發表於2016-08-31
Post Office
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 18680   Accepted: 10075

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

Source

---------------------
在村莊內建郵局,要使村莊到郵局的距離和最小
---------------------
f[i][j]表示前i個村莊中建j個郵局的最小距離,考慮最後一個郵局的位置
f[i][j]=min{f[k][j-1]+l[k+1][i]}
l可以遞推,建在中點最好,發現l[i][j]=l[i][j-1]+a[j]-a[(i+j)/2]成立
注意預處理
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int V=305,P=35,INF=1e9;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int v,p,a[V],l[V][V],f[V][P];
void dp(){
    for(int i=1;i<=v;i++)
        for(int j=i+1;j<=v;j++)
            l[i][j]=l[i][j-1]+a[j]-a[(i+j)/2];
    for(int i=1;i<=v;i++) for(int j=0;j<=v;j++) f[i][j]=INF,f[i][1]=l[1][i];
    for(int i=1;i<=v;i++)
        for(int j=1;j<=p;j++){
            for(int k=1;k<i;k++)
                f[i][j]=min(f[i][j],f[k][j-1]+l[k+1][i]);
        }
}
int main(int argc, const char * argv[]) {
    v=read();p=read();
    for(int i=1;i<=v;i++)a[i]=read();
    dp();
    printf("%d",f[v][p]);
    return 0;
}

 

相關文章