Learn to use divide and conquer algorithm to solve the problem of post office location (Java implementation)

Post office location problem (divide and conquer algorithm)


Preface

Tip: In the process of algorithm learning, we will encounter a variety of algorithm ideas, the most common of which is the idea of ​​divide and conquer algorithm, and the problem of post office location in this article is a daily implementation based on the idea of ​​divide and conquer. problem


Tip: The following is the content of this article, I will describe the problem in detail

1. What is the divide and conquer algorithm?

In general, the divide-and-conquer algorithm decomposes a large-scale problem that is difficult to solve directly into several smaller-scale sub-problems, and breaks each one, divide and conquer.

Insert picture description here
Combine the solved solutions of the smaller-scale problem into a larger-scale problem solution, and find the solution of the original problem from the bottom up.
Insert picture description here

2. The basic idea of ​​divide and conquer algorithm

1. The basic idea of ​​divide and conquer strategy

1. Divide or reduce the original problem into smaller sub-problems 2. Solve each sub-problem recursively or iteratively 3. Synthesize the solutions of the sub-problems to obtain the solution of the original problem

2. Note:

1. The properties of the
subproblems are exactly the same as the original problem. 2. The subproblems can be solved independently of each other.
3. The subproblems can be solved directly when the recursion stops.

3. Location of post office

Problem description:
In a city that is divided into regular blocks in the east-west and north-south directions, n residential areas are scattered in different blocks. Use the x coordinate to indicate the east-west direction, and the y coordinate to indicate the north-south direction. The location of each residential point can be represented by coordinates (x, y). Requirement: select the site for the post office, so that the sum of the distances between n residential areas and the post office is the smallest.
Tip:
Weighted median

Code :

package Site_selection;
import java.io.BufferedReader;
import java.io.FileReader;

public class Site_selection {
    
    
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int N=0;
		int x[]=new int[500];    //存放测试样本中x轴的数据值
		int y[]=new int[500]; 
		int xweight[]=new int[500];//存放测试样本中的权值
		int yweight[]=new int[500];
        for(int a=1;a<7;a++) {
    
    
        try {
    
    
    	  System.out.println("测试样本"+a);
    	  FileReader filereader=new FileReader("input0"+a+".txt"); //采用拼接方式读取样本
    	  BufferedReader buf=new BufferedReader(filereader);
    	  int j=0;
    	  String readline="";
    	  String[] array=new String[200];
    	  readline=buf.readLine();
    	  N=Integer.parseInt(readline);//读取测试样本中的第一行居民点的个数
    	  System.out.println("居民点个数为:"+N);
    	  while((readline=buf.readLine())!=null) {
    
    
    		  array=readline.split(",");  	//按照,分隔字符串来放入相应的数组之中
    	      x[j]=Integer.parseInt(array[0]);
    		  y[j]=Integer.parseInt(array[1]);
    		  xweight[j]=Integer.parseInt(array[2]);
    		  yweight[j]=Integer.parseInt(array[2]);
    		  j++;  		 
    	  } 
      }
      catch(Exception e) {
    
    
    	 e.printStackTrace();
      }
      MinSumDistance(x,y,xweight,yweight,N);
     }
	}
	/*
	 * 1.快速排序
	 *   通过该排序方式中的分治思想,来对测试样本中所有的数据值进行相对应的排序
	 * 
	*/
    public static void QuickSort(int a[],int weight[],int low,int high){
    
    
    	if(low>high) {
    
    
    		return;
    	}
    	int first=low;
    	int last=high;
    	int key=a[first];
    	int Weight=weight[first];
    	while(first<last)
    	{
    
    
    		while(first<last&&a[last]>key) {
    
    
    			--last;
    		}
    		a[first]=a[last];
    		weight[first]=weight[last];
    		while(first<last&&a[first]<key) {
    
    
    			++first;
    		}
    		a[last]=a[first];
    		weight[last]=weight[first];
    	}
    	a[last]=key;
    	weight[last]=Weight;
    	QuickSort(a,weight,low,first-1);
        QuickSort(a,weight,first+1,high);    	 	
    }
    /*
     * 2.邮局到居民点的最短路径之和
     *   通过对x轴与y轴的带权中位数的求解来得到相应的邮局坐标,再通过坐标位置与各个居民点的坐标位置相运算累加之和即为最短距离
     * 
     * 
     */
    public static void MinSumDistance(int x[],int y[],int xweight[],int yweight[],int N) {
    
    
    	int x1=0;
    	int y1=0;
    	int distance = 0;
    	QuickSort(x,xweight,0,N-1);
    	int sumxweight=0;
    	int sumyweight=0;
    	for(int b=0;b<xweight.length;b++) {
    
    
    		sumxweight+=xweight[b];
    	}
    	System.out.println("x坐标上的总权值为:"+sumxweight);
    	for(int i = 0; i < xweight.length; i++){
    
    
			sumxweight += xweight[i];
			if(sumxweight >= sumxweight / 2){
    
    x1=i;break;//求取x轴上的带权中位数
				 }
			}
    	System.out.println("邮局的x坐标为:"+x[x1]);
    	QuickSort(y,yweight,0,N-1);
    	int sumyWeight=0;
    	for(int b=0;b<yweight.length;b++) {
    
    
    		sumyWeight+=yweight[b];
    	}
    	System.out.println("y坐标上的总权值为:"+sumyWeight);
    	for(int k = 0; k < yweight.length; k++){
    
    
			sumyweight += yweight[k];
			if(sumyweight >= sumyweight / 2){
    
    y1=k;break;//求取y轴上的带权中位数
				 }
			}
    	System.out.println("邮局的y坐标为:"+y[y1]);
    	System.out.println("邮局的坐标位置为"+x[x1]+","+y[y1]);
    	for(int q=0;q<N;q++) {
    
    
    		distance+=Math.abs((x[q]-x[x1]))+Math.abs((y[q]-y[y1]));
    	}
    	System.out.println("所有居民点到邮局的最短距离为:"+distance);
    	System.out.println("------------------");
    }
}

Operation description: The
post office location problem is analyzed by analyzing the coordinate location of the residential area and the weight of the number of residents. In the input data, first enter the number of residential areas in the test sample, and then input the coordinate locations of each residential area and The number of residents. After running the program, the output result will be the coordinate position of the post office and the sum of the shortest paths from the post office to all the residential areas.

operation result:
Insert picture description here

Summarize algorithm design ideas

The program mainly adopts the idea of ​​divide and conquer, including a quick sorting method, sorting the x-coordinates in the input data values ​​from small to large, so that the weights corresponding to the x-coordinates are also sorted accordingly. Then select the corresponding x-coordinate by half the sum of the weights, find the weighted median, and find the y-coordinates of the data in the same way, and finally calculate the distance operation for the coordinates of each residential point through the obtained post office coordinates , The accumulated result is the sum of the shortest distances from the post office to all residential areas.

Guess you like

Origin blog.csdn.net/Xiao_ni_tongxue/article/details/109255860