算法设计与分析: 2-3 邮局选址问题

2-3 邮局选址问题


问题描述

在一个按照东西和南北方向划分成规整街区的城市里,n个居民点散乱地分布在不同的街区中。用x 坐标表示东西向,用y坐标表示南北向。各居民点的位置可以由坐标(x,y)表示。街区中任意2 点(x1,y1)和(x2,y2)之间的距离可以用数值|x1-x2|+|y1-y2|度量。
居民们希望在城市中选择建立邮局的最佳位置,使n个居民点到邮局的距离总和最小。

编程任务:
给定n 个居民点的位置,编程计算n 个居民点到邮局的距离总和的最小值。


分析

二维邮局问题,可以转化为两个一维邮局问题,可用中位数原理,同输油管道问题


Java

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int postOffices = 5;
        int[][] points = {{1, 2}, {2, 2}, {1, 3}, {3, -2}, {3, 3}};
        int[] pointX = new int[postOffices];
        int[] pointY = new int[postOffices];

        for(int i=0; i<postOffices; i++){
            pointX[i] = points[i][0];
            pointY[i] = points[i][1];
        }

        //sort point x & y
        Arrays.sort(pointX);
        Arrays.sort(pointY);

        //sorted point x
        System.out.println("Sorted point x: ");
        for(int i=0; i<postOffices; i++){
            System.out.println(pointX[i]);
        }

        //sorted point y
        System.out.println("Sorted point y: ");
        for(int i=0; i<postOffices; i++){
            System.out.println(pointY[i]);
        }

        int distX=0;
        int distY=0;
        int medianX, medianY;//中位数
        if(postOffices%2 == 1){
            medianX = pointX[postOffices/2];
            medianY = pointY[postOffices/2];
            for(int i=0; i<postOffices; i++){
                distX += Math.abs(pointX[i]-medianX);
                distY += Math.abs(pointY[i]-medianY);
            }
        }else {
            medianX = pointX[postOffices/2] + pointX[postOffices/2-1];
            medianX /= 2;

            medianY = pointY[postOffices/2] + pointY[postOffices/2-1];
            medianY /= 2;
            for(int i=0; i<postOffices; i++){
                distX += Math.abs(pointX[i]-medianX);
                distY += Math.abs(pointY[i]-medianY);
            }
        }

        int dist = distX + distY;

        System.out.println("The shortest distance is: "+dist);
    }
}

output

Sorted point x: 
1
1
2
3
3
Sorted point y: 
-2
2
2
3
3
The shortest distance is: 10

王晓东《计算机算法设计与分析》(第3版)P42

猜你喜欢

转载自blog.csdn.net/ioio_/article/details/80952533
今日推荐