dp:post office-邮局选址

来源:互联网 发布:2013蛇年新疆网络春晚 编辑:程序博客网 时间:2024/05/17 02:45

Post Office

poj1160

Time Limit: 1000MS Memory Limit: 10000K

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


题目大意:
给你一个递增的数组,代表每一个居民居住的位置,让你分配p个邮局地址使得所有居民到离他最近的邮局的距离总和最小,注意邮局可以盖在居民楼的位置。

题目思路:
dp想法。
当只有一个邮局的时候,可以邮局应该放在从左到右第v/2的居民楼上的答案是最优的。当有v个邮局的时候,在前v个村庄中建立j个邮局的最短距离,是在前i个村庄中建立j-1个邮局的最短距离与在j+1到第i个邮局建立一个邮局的最短距离的和。建立一个邮局的答案可以预先处理。

附上代码:

#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespace std;int main(){    int v, p, a[1005]={0}, dp[305][50], sum[305][305];    cin >> v >> p;    memset( sum, 0, sizeof(sum) );    for( int i=0 ; i<v ; i++ ){        for( int j=0 ; j<=p ; j++ )            dp[i][j] = 1<<29;    }    for( int i=0 ; i<v ; i++ ){        scanf( "%d", &a[i] );    }    for( int i=0 ; i<v ; i++ ){        for( int j=i+1 ; j<v ; j++ ){            int pos = (i+j)/2;            for( int k=i ; k<=j ; k++ )                sum[i][j] += abs( a[k]-a[pos] );        }    }    for( int i=0 ; i<v ; i++ ) dp[i][1] = sum[0][i];    for( int i=0 ; i<v ; i++ ){        for( int j=2 ; j<=p ; j++ ){            for( int k=0 ; k<=i ; k++ ){                dp[i][j] = min( dp[k][j-1]+sum[k+1][i], dp[i][j] );            }        }       }    cout << dp[v-1][p] << endl;    return 0;} 
0 0
原创粉丝点击