您的位置:首页 > 其它

ACM: 动态规划 poj 1160 终于有点…

2016-05-19 23:20 417 查看
                                                                 
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个当作邮政局, 使得每个点到最近的邮政局的为它的距离差的绝对值.

      现在要全部点距离和最小.

解题思路:

         1. 动态规划题, 先找规划状态: dp[i][j]: 前i个村庄设置j个邮政局的最小距离差和.

         2. 动态转移方程: dp[i][j] = min(dp[i][j],dp[k][j-1]+dist[k+1][j]);

                        dist[k+1][j]: 表示点k+1到点j的邮政设置一个的时候点的最小距离.

                        (j-1 <= k <= i-1)

         3. dist[i][j]可以通过预处理实现.

代码:

#include <cstdio>

#include <iostream>

#include <cstring>

using namespace std;

#define MAX 303

const int INF = (1<<30);

int n, m; // n: point, m: post office;

int a[MAX];

int dist[MAX][MAX];

int dp[MAX][MAX];

inline int min(int a,int b)

{

    return a < b ? a : b;

}

int abs(int a)

{

    return a > 0 ? a : -a;

}

int main()

{

//    freopen("input.txt","r",stdin);

    while(scanf("%d %d",&n,&m) != EOF)

    {   

        memset(dist,0,sizeof(dist));

        for(int i = 1; i <= n; ++i)

        {

            scanf("%d",&a[i]);

        }

       

        for(int i = 1; i <= n; ++i)

        {

            for(int j = i+1; j <= n; ++j)

            {

                int mid = (i+j)/2;  //取i,j的中点.

                for(int k = i; k <= j; ++k)

                {

                    dist[i][j] += abs(a[k]-a[mid]);

                }

            }

        }

       

       
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: