Implementing an Algorithm using Java

Source: Internet
Author: User

"Java" implements an algorithm previously feed using Java

In the process of learning Java, one of my friends threw me an algorithm problem, in order to test their learning of Java I decided to use Java to solve this algorithm problem.

Specific questions

There is a K-fork tree, we know its pre-sequence traversal and post-order traversal, also know the value of K, to find out how many possible forms of K-fork tree. such as 113 fork tree, the pre-sequence traversal is Abejkcfghid, the post-order traversal is JKEBFGHICDA, then its possible shape has 207352860 kinds.

Problem analysis

According to the definition of traversal we can know:

    1. The first letter of the pre-sequence traversal and the last letter of the post-order traversal is his root.

    2. The next letter of the root of the pre-sequence traversal is its leftmost subtree.

    3. The previous letter of the root of the subsequent traversal is its rightmost subtree.

Take the title as an example: (Here we start with the post-order traversal)

    1. A is the root of the tree, D is the right subtree of a, and the remaining letters are descended from A;

    2. With D as root, the descendant of D on the right of D in the sequence Traversal (none), D's brother on the left and the descendant of D (i.e., Bejkcfghi), where C is the rightmost subtree except D.

    3. c is the root, in the previous sequence traversal C to the right of the descendants of C (ie, Fghi), C left for the left of the brothers and their descendants (ie, BEJK), C descendants of the former sequence traversal of Fghi, post-order traverse to fghi,i as the right subtree of C; The post-order traversal is JKEB. B is the right subtree of a in addition to d,c;

    4. First of all, the brothers and their descendants on the left of C, B is a sub-tree, C, D brothers, E is a sub-tree of B, J, K is the subtree of E;

    5. Treatment of the descendants of C, according to the above treatment method is easy to f, G, H, I are all C subtree;

    • , visible A has 3 subtrees, B has 1 subtrees, C has 4 subtrees, and E has 2 subtrees. Because it is a 13-fork tree, when a root node has n sub-tree, then the node and the sub-tree arrangement probability is C (n,13), so the total possible shape of the 13 fork tree is C (3,13) * C (1,13) * C (4,13) * C (2,13) = 207352860.

    • Summing up the process above, what we need is a way to keep the K-fork tree constantly split and to find out the number of tree nodes in each root node.

Program implementation

First, we have to understand what we need:

    1. A main class that initializes the data we need, including the K, the pre-sequence traversal, and the post-order traversal of the topic, and, preferably, the final processing result and output.

    2. We need to use a lot of C (n,k) during the analysis, and if each C (n,k) is a separate operation, we can use an array to calculate and store them.

    3. The following nature is the play, through the method to implement the algorithm. This method:

1. Need to be able to determine the root node according to the given pre-sequence traversal and post-order traversal;

2. Split the pre-sequence traversal and post-order traversal through the root node, and compute the number of each tree of root nodes;

3. Be able to call themselves, because splitting themselves is going to be recycled, and we also need an array to record how many roots, each with how many subtrees, this array should obviously be independent of the method.

Actual program
public class Qianhou {//primary class public static void Main (string[] args) {String Qian = "Abejkcfghid               ";    Initialize input String hou = "JKEBFGHICDA";        byte k = 13;                             Long poss = 1;          Result Char [] DLR = Qian.tochararray ();           In Java, it is easy to manipulate a string type into a char array using complex, char [] lrd = Hou.tochararray ();                     DLR pre-sequence traversal, LRD post-order traversal Jisuan a1 = new Jisuan ();                  Int[] Zuh=a1.setarray (k);                           The combined number results of the method calculation A1.find (DLR,LRD);    for (int i=1; i<a1.ccount+1; i++) {//calculation result poss = poss * Zuh[a1.acco[i]];  } System.out.println (poss);                   }} class jisuan{int[] Acco = new int[10000]; The new array records the number of tree nodes (you can also use ArrayList, although it is troublesome to give the value + + in the ArrayList array, but you can control the array size.)                            Note cannot be written in the method int ccount = 0;        ACCO array pointer public int[] SetArray (byte k) {//record C (n,k) value array int[] Zuhe = new int[k+1];        Zuhe[0] = 1; For (inT I=1; i<=k;              i++) {Zuhe[i] = 1;        Zuhe[i] =zuhe[i-1]* (k+1-i)/I;    } return Zuhe;              } public void Find (char[] DLR, char[] lrd) {//Call object should be a pre-order traversal with post-ordering traversal, because there is complete information int i1 = 0, i2=0, i3 = 0;                    Initialize pointer int l = dlr.length;         Initialize traverse length while (dlr[i1]! = Lrd[l-1]) {//Find the right subtree position i1++ in the pre-order traversal; }//Here due to the time relationship, not using try to verify the initial condition is reasonable, should be supplemented if (l! = 1) {//If the length of 1 is no subtree, do not need to continue to split if (i1!=0)    {//If the right-most subtree has a position not 0 in the pre-order traversal, indicating that there is no left sibling and its descendants, left without splitting char[] LDLR = new CHAR[I1];                char[] llrd = new CHAR[I1] for the left sibling and its descendants in the pre-sequence traversal and post-order traversal segmentation;                    for (i2=0; i2<i1;i2++) {Ldlr[i2] = Dlr[i2];                LLRD[I2] = Lrd[i2]; } Acco[ccount] = acco[ccount]+1;               Root subtree number +1 find (LDLR,LLRD);            Split the left sibling and its descendants first, traversing all the siblings of the root, without a lot of control over the pointer to the array of records} if (I1!=L-1) {//If the rightmost subtree is not at the end of the previous sequence traversal, no descendants are indicated, the right side does not need to be split char[] RDLR = new char[l-                i1-1];//the pre-sequence traversal of its descendants and the post-order traversal segmentation char[] rlrd = new Char[l-i1-1];                    for (i3=0; i3<l-i1-1;i3++) {Rdlr[i3] = Dlr[i3+1+i1];                RLRD[I3] = Lrd[i3+i1];                      } ccount++;              The array pointer points to the next root acco[ccount] = 1;            Root subtree number +1 find (RDLR,RLRD); }        }    } }
Summarize

Java is not suitable for writing algorithms, but because of these obstacles and constraints, write algorithms to meet more problems, in the process of solving these problems, but can more deeply understand the inherent logic of Java and its own flaws.

    • This is probably the so-called time is the only criterion to test the truth ...

Implementing an Algorithm using Java

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.