Since the beginning of the public number began, has been thinking, how to do the training of the algorithm, because the thinking of the students in the algorithm this aspect of the mastery is indeed not enough. Therefore, I now want to do a "365 Algorithm daily Learning Plan".
The main purpose of the plan:
1, want to through this way to supervise their own more efforts to learn the algorithm.
2, want to and small partners "group" together to learn the exchange of learning algorithms in the process of drip. “
The main content of the program:
1, the basic knowledge of data structure and algorithm is consolidated.
2, progressive step of the OJ algorithm training. Schedule: Every Wednesday and Saturday article is a bit long, hope to be patient to read.
--Say in front
"Algorithm Daily Learning" program 01 Punch-In:
Problem description
A positive integer n is known, asking for three numbers from 1~n, and the maximum number of least common multiple they can have. Input format
Enter a positive integer n. Output format output An integer that represents the least common multiple you found. Sample input 9 Sample output 504 data size and conventions
1 <= N <= 106.
The thinking and realization of solving problems
The following idea is given by the small partners of the "Algorithmic Daily Learning Exchange Community", thanks to the support and attention of our small partners.
Thinking Analysis:
Maximum least common multiple, Lenovo to two number of the maximum least common multiple, that is, the product of two numbers (note: two consecutive natural numbers are mutually exclusive).
Again, we can take the last three numbers for consideration.
1. When n is odd, the n,n-1,n-2 is odd even, with only an even number, so there is no 2 factor. The three-digit difference is less than 3, so there is no factor 3, so it conforms to test instructions.
2. When n is even, the n,n-1,n-2 is even parity, at this time n,n-2 must contain a factor of 2, so except for 2 is not worth. So consider converting n-2 to n-3, and then to odd and even odd, there is a problem at this time,
N and N-3, if n%3==0, is not worth more than 3. Still according to the principle of parity, the change of even N is n-2, at this time replaced by n-1,n-2,n-3 and 1 case. Therefore, it complies with test instructions.
So according to the above analysis, we can write the following code:
1import java.util.scanner; 2public class main{ 3 public static void main (String[] args) { 4 scanner scanner = new scanner (system.in); 5 long n = scanner.nextlong (); 6 long result; 7 if (n<3) 8 result=n; 9 else{ 10 if (n%2!=0) 11 result=n* (n-1) * (n-2); 12 else if (n%3!=0) 13 result=n* (n-1) * (n-3); 14 else 15 result= (n-1) * (n-2) * (n-3); 16 } 17 &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (result); 18 }19}
In fact, the above algorithm is to use the greedy thought , presumably this way of thinking :
Starting with the largest number of three, if the maximum number is odd, then there are two odd numbers in the adjacent three digits, greatest common divisor is 1, and least common multiple is n (n-1) (n-2). If the number is even, then move backward, consider N (n-1) (n-3), then N and n-3 difference 3, the condition is satisfied that n can not be divisible by 3, otherwise the result can only be (n-1) (n-2) (n-3).
This topic because of the use of greedy ideas, so the following introduction to the greedy algorithm .
Greedy algorithm One, the basic concept:
The so-called greedy algorithm refers to, in the problem solving, always make the best choice at present. In other words, not considering the overall optimality, he makes only the local optimal solution in a certain sense.
Greedy algorithm has no fixed algorithm framework, the key of algorithm design is the choice of greedy strategy. It must be noted that the greedy algorithm does not have the overall optimal solution to all problems, the greedy strategy chosen must have no effect, that is, the process after a state does not affect the previous state, only related to the current state.
Therefore, the greedy strategy used must carefully analyze whether it satisfies the no-effect.
Second, the basic idea of greedy algorithm:
1. Build a mathematical model to describe the problem. 2. Divide the problem of solving into several sub-problems. 3. To solve each sub-problem, the local optimal solution of sub-problem is obtained. 4. The solution of the problem is solved by the local optimal solution to the original solution problem.
Three, the greedy algorithm applies the question
The premise of greedy strategy is that local optimal strategy can lead to global optimal solution.
In fact, greedy algorithms are rarely used. In general, whether a problem analysis is applicable to greedy algorithm, you can choose the problem of a few real data analysis, you can make judgments.
Four, greedy algorithm implementation framework
1 starting from an initial solution of the problem; 2 while (one step ahead of a given total target) 3 {4 A solution element of the feasible solution is obtained by using the feasible decision; 5}6 a feasible solution with all the solution elements;
Five, the choice of greedy strategy
Because the greedy algorithm can only solve the global optimal solution by solving the local optimal solution, we must pay attention to whether the problem is suitable for the greedy algorithm and whether the solution found is the best solution.
Vi. Analysis of examples
Here is a greedy algorithm can be tried to solve the problem, greedy solution is really good, but not the optimal solution.
example ①[knapsack problem] There is a backpack, backpack capacity is m=150. There are 7 items that can be divided into any size. It is required to maximize the total value of the items loaded into the backpack, but not to exceed the total capacity. Item A B C D E F g weight 35 30 60 50 40 10 25 Value 10 40 30 50 35 40 30
Analysis: objective function: ∑PI The maximum constraint is that the total weight of the loaded item does not exceed the backpack capacity:∑wi<=m (m=150)(1) According to the greedy strategy, each time to pick the most valuable items loaded into the backpack, Are the results optimal? (2) Can the optimal solution be obtained for each item with the smallest weight selected? (3) Each time the unit weight value of the most valuable items, become the solution of the strategy.
It is worth noting that the greedy algorithm is not completely not available, once the greedy strategy has been proved, it is an efficient algorithm. Greedy algorithm is also a very common algorithm, this is because it is simple, the construction of greedy strategy is not very difficult.
Unfortunately, it needs to be proven before it can really be used in the algorithm of the problem.
In general, the proof of greedy algorithm revolves around: the optimal solution of the whole problem must be obtained by the optimal solution of the sub-problem in the greedy strategy. For the 3 kinds of greedy strategies in the example, it is impossible to set up (can not be proved), explained as follows:
(1) Greedy strategy: Choose the most valuable person. Counter Example:
W=30 Item: A B C Weight: 28 12 12 Value: 30 20 20
According to the strategy, first select Item A, then you can no longer select, however, choose B, C is better.
(2) Greedy strategy: Choose the smallest weight. Its inverse example is similar to the first strategy's counter example. (3) Greedy strategy: Select items with the greatest value per unit weight. Counter Example:
W=30 Item: A B C Weight: 28 20 10 Value: 28 20 10
According to the strategy, three items per unit weight value, the program can not be judged according to the existing policy, if you choose a, the answer is wrong.
example ②[-divided cards] have n piles of cards, numbered 1,2,...,n. There are several sheets on each heap, but the total number of cards must be multiples of n. You can take several cards on either heap and move them. The rules for the move are: the cards taken on the number 1 can only be moved to the heap numbered 2, and the cards taken on the heap numbered n can only be moved to the heap numbered n-1, and the other stacks will be moved to the adjacent left or right heap. Now it's time to find a way to move, with the fewest number of moves to make as many cards as you can on each heap. For example: n=4,4 heap cards are: ①9②8③17④6 move three times can achieve the purpose: from the ③ take 4 cards to ④ and then from the ③ area 3 to ② and then from ② 1 to ①.
Input/Output Sample: 4
9 8 17 6
Screen display: 3
algorithm Analysis: set A[i] is the number of cards in the heap (0<=i<=n), V is divided after the number of cards per stack, S is the minimum number of moves.
We use the greedy algorithm to move the cards in order from left to right. If the number of cards in the heap is not equal to the average, move once (i.e. S plus 1) and move in two cases:
1. If a[i]>v, the A[i]-v sheet is moved from the heap I to the i+1 heap; 2. If A[i]<v, the v-a[i] sheet is moved from the I+1 heap to the first heap.
For the convenience of the design, we consider these two cases to be unified as moving a[i]-v from the first heap to the i+1 heap, after moving a[i]=v; a[I+1]=a[I+1]+a[i]-v
.
In the process of removing the stack of cards from the i+1 heap, it is possible to return to the i+1 heap of cards less than 0.
such as N=3, the three-heap assignment is 1 2 27, then v=10, in order to make the first heap of 10, to move from the second pile 9 to the first heap, and the second pile only 2 can move, does this mean that the use of greedy method is wrong?
We continue to follow the rules analysis of the move, from the second pile 9 to the first pile, the first pile of 10, the second pile of 7, moving from the third pile 17 to the second pile, just three piles of cards are 10, the final result is right, we in the process of moving, just change the order of movement, and the number of mobile inconvenience, So this problem is feasible using greedy method.
Java source Program
1public class Greedy { 2 public static void Main (String[] args) { 3 int n = 0 , avg = 0, s = 0; 4 scanner scanner = new scanner (system.in); 5 Arraylist<integer> array = new arraylist<integer> (); 6 system.out.println ("Please input the number of heaps:") ; 7 n = scanner.nextint (); 8 system.out.println ("Please input heap number:"); 9 for (int i = 0; i < n; i++) {10 array.add (Scanner.nextInt ());11 }12 for (int i = 0; i < array.size (); i++) {13 avg += array.get (i);14 }15 avg = avg / array.size ();16 system.out.println (Array.size ());17 &NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (avg);18 for (int i = 0; i < array.size () - 1; i++) {19 s++;20 arraY.set (I + 1, array.get (i + 1) + array.get (i) - avg);21 }22 System.out.println ("s:" + s); 23 }24}
To solve the problem with greedy algorithm, two problems need to be solved:
first, whether the problem is suitable to be solved by greedy method. Let's look at a coin-finding example, if a monetary system has three denominations, one angle, five points, and one point, which can be solved by greedy method when the minimum number of coins is found; If you change these three currencies to 1.1 cents, five and one, you cannot use the greedy method to solve them. It is very convenient to solve problems by greedy method, but its application scope is very small, judging whether a problem is suitable to be solved by greedy method, there is no general method in the contest of informatics, it needs to judge by personal experience.
The second is to determine the greedy algorithm can be used, how to choose a greedy standard, to ensure that the best solution to the problem. When choosing a greedy standard, we need to validate the chosen greedy criteria to be used, not to be fooled by seemingly correct greedy standards, as in the example below.
example ③[Maximum integer] has n positive integers, joins them in a row, forming one of the largest multi-bit integers.
For example: n=3, 3 integers 13,312,343, the maximum number of integers is 34331213.
Also such as: n=4, 4 integer 7,13,4,246, the largest integer is 7424613.
Input: nn number output: number of multiple digits connected
Algorithm Analysis: This problem is very easy to think of using greedy method, in the exam there are many students to the whole number from the big to the small sequence of connections, test questions are also in line with the example, but the final test results are not all right. According to this standard, we can easily find a counter example: 12,121 should be composed of 12121 instead of 12112, then is not mutually inclusive when the small to large? Not necessarily, such as 12,123 is 12312 instead of 12123, this situation has many kinds of. Is not this question can not use greedy method?
In fact, this problem can be solved by greedy method, just the standard is wrong, the correct standard is: first convert integers into strings, and then compare a+b and B+a, if A+b>=b+a, put a in front of B, and vice versa, a row in the back of B.
Java source Program
1public static void main (String[] args) { 2 String str = ""; 3 Arraylist<string> array = new arraylist<string> (); 4 scanner in = new scanner (system.in); 5 system.out.println ("please input the number of Data: "); 6 int n = in.nextint (); 7 system.out.println ("Please input the data:"); 8 while (n-- > 0) { 9 array.add (In.next ());10 }11 for (int i = 0; i < Array.size (); i++) 12 for (int j = i + 1; j < array.size (); j++) {13 if ((Array.get (i) + array.get (j)). CompareTo (Array.get (j) + array.get (i) < 0) {14 String temp = array.get (i);15 array.set (I, array.get (j));16 Array.set (j, temp); 17 }18 }19 for ( Int i = 0; i < array.size (); i++) {20 str += array.get (i);21 }22 system.out.println ("str=:" + str); 23 &NBSP;&NBSP;&NBSP;&NBSP;}24}
The choice of greedy algorithm can depend on the choice made in the past, but it never depends on the future choice, and does not depend on the solution of sub-problem, so the greedy algorithm has a certain speed advantage compared with other algorithms. If a problem can be solved in several ways at the same time, the greedy algorithm should be one of the best choices.
This is greedy some of the ideas and basic applications, if there are any problems, you can leave a message or private messages to me!
Resources
Recommended for previous period
"Interview unbeaten plan": Java language Foundation question (ii)
"365 Algorithm Daily Learning Plan": 02 Punch-In-Line table (books activity ① period trailer)
Concurrency Basics (i): Threading Introduction
"365 Algorithm Daily Learning Plan": 03 Punch-in-greedy algorithm