Classic algorithm Mark

Source: Internet
Author: User

In peacetime looking for work, more or less will encounter some algorithmic problems, many are more classic or online has been circulating for a long time. But we have not contacted, so do not know how to solve.

Here, I myself summed up some of the classic algorithms I met, to add a bit of memory, but also to the needs of friends to see learning.

1. pour water problem

Title: A cup with a capacity of 5 liters and a cup with a capacity of 3 liters, water is not limited to use, requires accurate 4 liters of water.

This type of problem generally has two ways to question:

A. A Brief Answer

Here's a brief answer: in fact, there are many kinds of results, and here is one of the least water-pouring times.

    

B. Programming implementation

Solution is also more, I first think of the DFS (depth first) search, each time we have 6 choices, as long as the constant attempt to continue, can always search all the state, find a solution. You can also use the width-first search (BFS).

The program code is subsequently mended.

  Follow-up also has other versions of the Pour water problem, such as: There are three containers, respectively, 20 liters, 13 liters, 7 liters. 20 liters of containers filled with water, to make 20 liters and 13 liters of containers 10 water respectively, how to do?

The simple steps are similar to the preceding:

    

2. The monkey chose the king question

Topic:

N Monkeys sit in a circle, numbered from 1 to n clockwise.
Then from the 1th monkey began to count in the clockwise direction from 1, reporting m of the monkeys out, and then from the first out of the monkey's next position to restart the count,
So repeat until one of the monkeys is left, and it is the king.

Design and write programs to achieve the following functions:
(1) required by the user input at the beginning of the number of monkeys $n, count the last number of $m.
(2) Give the initial number of the chosen Monkey King.

The immediate idea of this problem is the implementation of a circular link list, or an array implementation.

The following code is directly posted:

Solution 1:

1<?PHP2 $arr=Array(' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ');//Example Array3 Echo' <pre>the King is:<br/> ';4 Print_r(King ($arr, 11));5 functionKing$arr,$count){6     $i= 1;//starting from 17      while(Count($arr) > 1){8         if($i%$count= = 0) {//with the remainder, calculate the number to the bit, if the remainder is 0, the number of bits to eliminate, pressure in the group9             unset($arr[$i-1]);Ten}Else{//the digit is not the end, put this bit to the end of the array, and eliminate the bit One             Array_push($arr,$arr[$i-1]); A             unset($arr[$i-1]); -         } -         $i++;//move to the next array element the         Var_dump($arr); -         Echo' <br > '; -     } -     return $arr; +}

This is accomplished by using an array, and if the current number is not selected, move it to the end of the array. The complexity of the algorithm is high, when the data volume is large, the processing efficiency is low.

Solution 2:

1 /**2  *3 * @param int $n4 * Number of monkeys at the beginning5 * @param int $m6 * The last number reported7 * (the number of monkeys to check out, and then the next monkey from the ① began to count back)8 * @return int Monkey's initial number9  */Ten functionMonkeyselectking ($n,$m) One { A     //the initial number of monkeys cannot be less than 2 -     if($n< 2) { -         return false; the     } -      -     $arr=Range(1,$n); -     //divide the monkey into an array, the value of the array corresponds to the initial number of the monkey +     $unsetNum= 0; -     //define a variable to record the count of monkeys +      A      for($i= 2;$i<=$n*$m;$i++)  at     //the total number of cycles does not know how to calculate, -     { -         //However, because return is set in the loop, the $m* $len efficiency can also be -         foreach($arr  as $k=$v) { -             $unsetNum++;//every monkey, a monkey count +1 -                           in //When the monkey's count is equal to the elimination of the number: the elimination of monkeys (delete array elements) - //Count back 0 (next monkey starting from 1) to             if($unsetNum==$m) { +                 //echo "<pre>";//open comments to see the specific elimination process - //Print_r ($arr); the                 unset($arr[$k]); *                 //Eliminate Monkeys $                 $unsetNum= 0;Panax Notoginseng                 //return to zero -                 if(Count($arr) = = 1)  the                 //Judging the length of the array, if there is only one monkey left, return its value +                 { A                     return Reset($arr); the                 } +             } -         } $     } $ } -  - Var_dump(Monkeyselectking (100, 2));

The complexity of this algorithm is O (nm), which is relatively low when NM is large.

A simpler way to achieve this: also called Joseph Ring 's mathematical solution

principle :

There is one thing in common with either a linked list or an array implementation: to simulate the entire game process, not only is the program more annoying, but the time complexity is as high as O (nm), and when the n,m is very large (for example, millions, tens of thousands), there is almost no way to produce results in a short period of time. We noticed that the original problem was merely to ask for the serial number of the last winner, rather than to mock the whole process. Therefore, if we want to pursue efficiency, we must break the routine and implement a mathematical strategy.
In order to discuss the convenience, the problem is changed slightly, does not affect the original intention:

Problem description: N Person (number 0~ (n-1)), starting from 0 count, reporting (M-1) exit, the remainder continues to count off from 0. The winner's number.

We know that the first person (the number must be m%n-1) after the dequeue, the rest of the n-1 individuals formed a new Joseph Ring (starting with the person numbered k=m%n):
K k+1 k+2 ... n-2, n-1, 0, 1, 2, ... k-2
And at the beginning of the K is reported 0.

Now let's do a conversion of their numbers:
K--0
K+1-1
K+2-2
...
...
K-2-N-2
K-1-N-1

After the transformation has completely become the (n-1) personal count of the sub-problem, if we know the solution of this sub-problem: for example, X is the final winner, then according to the above table to turn this x back is not exactly the solution of n personal situation?! The formula to change back is very simple, I believe everyone can push out: X ' = (x+k)%n

How to Know (n-1) The solution of the problem of personal count off? Yes, as long as you Know (n-2) the individual's solution. (n-2) A personal solution? Of course, the first thing to ask (n-3)----This is obviously a backward problem! Okay, here's the idea, here's the recursive formula:

Make f[i] means I personally play the game reported M exit the last winner's number, the final result is naturally f[n]

Recursive formulas
f[1]=0;
f[i]= (f[i-1]+m)%i; (i>1)

With this formula, all we have to do is calculate the value of F[i] from the 1-n order, and the final result is f[n]. Because real life numbers always start from 1, we output f[n]+1

The Final Solution is:

1 /**2 * The mathematical solution of Joseph Ring3  */4 functionYuesefu ($n,$m) {5     $r=0;6      for($i= 2;$i<=$n;$i++) {7 8         $r=($r+$m)%$i;9     }Ten     return $r+1; One } A Print_r(Yuesefu (100,2));

The mathematical solution to Joseph's ring comes from: http://www.cppblog.com/Victordu/archive/2008/02/22/43082.html

Classic algorithm Mark

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.