Divide-and-conquer method-Recent distance problem Java implementation

Source: Internet
Author: User

Divide-and-conquer algorithm, there are many typical problems, such as recent point problem, linear selection problem, Integer division problem, large integer score problem, board coverage problem, round robin schedule, binary search, Strassen matrix multiplication, Hanoi and so on. Be prepared to take some time to solve these problems one by one and implement them in Java, starting with the nearest point problem. Find some code on the Internet, the title, such as "Java with brute force method and partition method to solve the recent problem", although the division, but not completely divided, so I re-implemented it.

First, basic ideas and strategies:

First of all, talk about the idea of divided treatment. Division, "Divide and Conquer," is to divide a complex problem into two or more of the same or similar sub-problems, and then the problem into smaller sub- problems ... until the last sub-problem can be solved simply, the solution of the original problem is the merger of the solution of the sub-problem . This technique is the basis for many efficient algorithms, such as sorting algorithms (fast sorting, merge sorting), Fourier transforms, etc. The smaller the problem, the easier it is to solve it directly, and the less computational time it takes to solve it.

divide and conquer by reducing the size of the problem, conquer the problem, the strategy is: for a size of n problem, if the problem can be easily solved (for example, the size of n Smaller) is solved directly, otherwise it will be decomposed into K Small sub-problems, these sub-problems are independent and the same as the original problem, the recursive solution of these sub-problems, and then the solution of the sub-problems are combined to obtain the solution of the original problem .

Ii. circumstances in which the Division and Administration Law applies

The problems that can be solved by the method of division and administration generally have the following characteristics:

1 The scale of the problem is reduced to a certain extent and can be easily resolved

2 The problem can be decomposed into several small-scale same problems, that is, the problem has the best substructure properties .

3 The solution of sub-problems decomposed by this problem can be combined into the solution of the problem;

4 each sub-problem of the problem is independent of each other, that is, the sub-problem does not include the common sub-sub -problem.

The first characteristic is that most problems can be satisfied, because the computational complexity of the problem is usually increased with the increase of the size of the problem;

The second feature is the premise of applying the method of division and Treatment . It is also the most problems can be satisfied, this feature reflects the application of recursive thinking;

The third feature is the key, whether the use of divide-and-conquer method depends entirely on whether the problem has a third feature , if the first and second features, and does not have a third feature, you can consider using greedy or dynamic programming method .

The fourth feature relates to the efficiency of division and Treatment , if the sub-problems are not independent, then divide and conquer the law to do a lot of unnecessary work, repeated to solve the common sub-problem, although the use of divided treatment method, but generally with the dynamic programming method is better .

Third, the basic steps of the Division and Treatment law

The divide-and-conquer method has three steps on each level of recursion:

Step1 decomposition: Decomposition of the original problem into several small, independent, and the original problem form the same sub-problem;

Step2 Solution: If the sub-problem is small and easy to solve the direct solution, or recursively solve each sub-problem

Step3 Merging: The solution of each sub-problem is merged into the solution of the original problem.

Iv. taking the nearest point problem as an example

nearest point to question: N points on a given plane to find the two closest points. Without careful analysis of the efficiency and optimization process of the algorithm, the solution of the problem is directly discussed:

0 If the length of the array (that is, the number of points) within a certain range of the nearest point directly, pretty trying to solve

1 Find the median of the x-coordinate of these points mid

2 All points are divided into two groups in mid, and the table is placed in table T1 , T2

3 Convert the T1, T2 tables to arrays S1, S2, and S1, S2 in ascending order of x-coordinates , respectively

4 Finding the nearest distance of points in S1

5 Finding the nearest distance to the midpoint of S2

6 4, 5, the minimum value of two distances, recorded as D1

7 in S1, S2 collect the distance midline (x=mid) less than D1 points, respectively, stored in the table T3 , T4

8 Convert the table T3, T4 to the array type S3, S4, and S3, S4 in ascending order of y coordinates respectively

9 Find the possible nearest distance between S3 and S4 (compare with D1)

Five, code reference

Package Ly.ccnu.algorithmdesign;import Java.util.arraylist;import Java.util.random;import java.util.Set;import Java.util.treeset;public class Devideandconquer {/** * Recent points * @param S */public static point[] Closestpoint (Point [] S) {P Oint[] result = new point[2];/** * 0. First, solve the boundary of the problem, when the array length within a certain range of the nearest point, pretty try to solve */double DMin = Double.positive_infinity;doubl E tmpmin = 0;if (s.length <=) {for (int i = 0, i < s.length; i + +) {for (int j = i + 1; j < S.length; J + +) {Tmpmin = Math.sqrt (Math.pow (S[i].getx ()-S[j].getx (), 2) + Math.pow (s[i].gety ()-S[j].gety (), 2); if (Tmpmin < DMin) {DMin = t Mpmin;result[0] = s[i];result[1] = S[j];}}} return result;} /** all points in the x-coordinate of the median */int MinX = (int) double.positive_infinity;//guaranteed to assume that the initial minimum value is large enough int maxX = (int) double.negative_infinity ;//guarantee that the initial maximum value is small enough for (int i = 0; i < s.length; i++) {if (S[i].getx () < MinX) MinX = S[i].getx (); if (S[i].getx () > MaxX) MaxX = S[i].getx ();} int midx = (MinX + maxX)/2;/** * 2. Divide all points into two groups by MIDX in two tables */arraylist T1 = new ARraylist (); ArrayList T2 = new ArrayList (); for (int i = 0; i < s.length; i++) {if (S[i].getx () <= midx)//Do you want = number? T1.add (S[i]); if (S[i].getx () > Midx) t2.add (S[i]);} /** * 3. Convert two tables to array type, and in ascending order by x coordinate */point [] S1 = new point[t1.size ()]; Point [] S2 = new point[t2.size ()]; T1.toarray (S1); T2.toarray (S2); MergeSort (S1, "X");//x-coordinates ascending mergesort (S2, "X");//ascending by x-coordinate/** * 4. Find two points of the nearest distance in S1] */point[= new  POINT[2];RESULT1 = Closestpoint (S1);/** * 5. Find two points of the nearest distance in S2 */point[] result2 = new POINT[2];RESULT2 = Closestpoint (S2);/** * 6. Find the minimum value of two nearest distances */double D1 = math.sqrt (Math.min (Math.pow (Result1[0].getx ()-Result1[1].getx (), 2) + Math.pow (Result1[0] . GetY ()-Result1[1].gety (), 2), Math.pow (Result2[0].getx ()-Result2[1].getx (), 2) + Math.pow (result2[0].gety ()-Result 2[1].gety (), 2)); if (Math.pow (Result1[0].getx ()-Result1[1].getx (), 2) + Math.pow (result1[0].gety ()-result1[1].gety (), 2) < Math.pow (Result2[0].getx ()-Result2[1].getx (), 2) + Math.pow (result2[0].gety ()-Result2[1].gety (), 2))result = Result1;elseresult = result2;/** * 7. Collect points in S1, S2 that are less than D1 in the median line, stored in two tables */arraylist T3 = new ArrayList (); ArrayList T4 = new ArrayList (); for (int i = 0; i < s1.length; i++) {if (Midx-s1[i].getx () < D1) T3.add (S1[i]);} for (int i = 0; i < s2.length; i++) {if (S2[i].getx ()-Midx < D1) {T4.add (s2[i]);}} /** * 8. Convert the table T3, T4 to the S3, S4 of the array type respectively, and arrange them in ascending order of y coordinates */point [] S3 = new Point [T3.size ()]; Point [] S4 = new Point [T4.size ()]; T3.toarray (S3); T4.toarray (S4); MergeSort (S3, "Y"), MergeSort (S4, "Y"),/** * Solving the possible closer (compared to S3) distances between S4 and D1, and the points that make up the distance */double d = Double.pos itive_infinity;for (int i = 0; i < s3.length; i + +) {for (int j = 0; J < S4.length; J + +) {if (Math.Abs (S3[i].gety ()-S4 [J].gety ()) < D1) {double tmp = MATH.SQRT (Math.pow (S3[i].getx ()-S4[j].getx (), 2) + Math.pow (s3[i].gety ()-S4[j].gety ( ), 2)); if (tmp < d) {d = tmp;result[0] = s3[i];result[1] = S4[j];}} }}return result;} private static void MergeSort (point[] A, String property) {point[] Temparray = new Point[a.length];mergesoRT (A, Temparray, 0, a.length-1, property);}  private static void MergeSort (point[] A, point [] temparray, int left, int. right, String property) {if (left < right) {int Center = (left + right) >> 1;//Division MergeSort (A, Temparray, left, center, property) MergeSort (A, Temparray, center + 1 , right, property);//Merging merge (A, Temparray, left, center + 1, right, property);}} private static void Merge (point [] A, point [] temparray, int leftpos, int. rightpos, int rightend, String property) {int Le Ftend = Rightpos-1;int numofelements = rightend-leftpos + 1;int tmppos = leftpos;//cursor variable, and the other two cursor variables are leftpos and RIGHTPOSW respectively Hile (leftpos <= leftend && rightpos <= rightend) {if (Property.equals ("x")) {if (A[leftpos].getx () <= a[ Rightpos].getx ()) temparray[tmppos++] = a[leftpos++];elsetemparray[tmppos++] = a[rightpos++];} else if (property.equals ("Y")) {if (A[leftpos].gety () <= a[rightpos].gety ()) temparray[tmppos++] = a[leftpos++]; elsetemparray[tmppos++] = a[rightpos++];} Elsethrow New RuntimeexcePtion ();} while (LeftPos <= leftend) temparray[tmppos++] = A[leftpos++];while (rightpos <= rightend) tempArray[tmpPos++] = a[ rightpos++];//copies the ordered paragraphs into the original array system.arraycopy (Temparray, Rightend-numofelements+1, A, rightend-numofelements+1, numofelements);} public static void Main (string[] args) {set<point> testData = new treeset<point> (); Random random = new random (), int x = 0;int y = 0;for (int i = 0;i < 600;i++) {x = Random.nextint (); y = Random.nextint (5 0); System.out.println ("x:" + x + "y:" + y); Testdata.add (new Point (x, Y));} Point [] S = new point[testdata.size ()]; s = (point[]) Testdata.toarray (s); for (int i = 0; i < s.length; i + +) {System.out.println ("(" + s[i].getx () + "," + s[i ") . GetY () + ")"); System.out.println (Testdata.size ()); Point [] result = new Point [2];result = Closestpoint (S); System.out.println ("The last two points were (" + result[0].getx () + "," + result[0].gety () + ") and (" + result[1].getx () + "," + result[1 ].gety () + "), Nearest Distance:" + math.sqrt (Math.pow (Result[0].getx ()-Result[1].getx (), 2) + Math.pow (result[0].gety ()-Result[1].gety (), 2));}} 

Package ly.ccnu.algorithmdesign;/** * Build your own class point */class Point implements Cloneable, Comparable<point>{public Point () {x = 0;y = 0;} public point (int x, int y) {this.x = X;this.y = y;} public void SetX (int x) {this.x = x;} public void sety (int y) {this.y = y;} public int GetX () {return x;} public int GetY () {return y;} private int x;private int y; @Overridepublic int compareTo (Point O) {if (x = = O.getx () && y = = o.gety ()) return 0;els e return 1;}}

VI. Legacy Issues

1, TreeSet has a repeating element

2, Stack Overflow java.lang.StackOverflowError (when the number of points is many, but concentrated in a region of time)

If the hero is lucky to see and found a solution to the problem, but also hope to teach!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.