As the name implies, the greedy algorithm always makes the best choice in the current view. That is to say, the greedy algorithm does not take the overall optimal consideration, it makes the choice is only in some sense the local optimal choice. Of course, it is hoped that the final result of greedy algorithm is also the overall optimal. Although the greedy algorithm cannot get the whole optimal solution for all problems, it can produce the whole optimal solution for many problems. such as single source shortest path through problem, minimum spanning tree problem, etc. In some cases, even if the greedy algorithm can not get the overall optimal solution, the final result is a good approximation of the optimal solution.
Question one, organization of activities
Problem statement: A set of n events E = {,..., n}, where each activity requires the use of the same resource, such as a lecture venue, and only one activity can use this resource at the same time. Each live I has a starting time that requires the use of the resource Si and an end time of fi, and si < fi. If active I is selected , it occupies resources within the half-open time interval [Si, fi]. If the interval [Si, FI) does not intersect with the interval [SJ, FJ], then the activity I is compatible with the active J. In other words, when si >= fj or sj >= fi, Activity i is compatible with activity J.
Because the input activity is arranged in a non-decreasing order of its completion time, the algorithm Greedyselector always selects a compatible activity with the earliest finish time to join the set a. Intuitively, selecting a compatible activity in this way leaves as much time as possible for the non-scheduled activity. In other words, the greedy choice of the algorithm is meant to maximize the remaining available time periods in order to arrange as many compatible activities as possible.
the algorithm greedyselector is highly efficient. When the input activity has been arranged in a non-descending order of the end time, the algorithm simply arranges n activities at the time of O (n) , allowing the most activities to use the public resources in a consistent manner. If the given activity is not in non-descending order, it can be rearranged with O (NLOGN) time.
Example: The start time and end time of the 11 activities to be scheduled are listed in the non-descending order of the end time as follows:
the computational process of the algorithm greedyselector is shown. Each row in the diagram corresponds to an iteration of the algorithm. A shaded bar represents an activity that has been selected into collection A, whereas a blank bar represents an activity that is currently checking for compatibility.
If the start time of the checked activity i si is less than the end time of the recently selected activity J , then the active I is not selected , otherwise the active I is selected to join the set a.
The greedy algorithm does not always obtain the overall optimal solution of the problem. But for the activity scheduling problem, the greedy algorithm Greedyselector can always obtain the overall optimal solution, that is, it finally determines the scale of the compatible activity set A is the largest. This conclusion can be proved by mathematical inductive method.
Event scheduling Problem Implementation:
Code
Basic elements of greedy algorithm
For a specific problem, how to know whether the greedy algorithm can solve the problem, and can get the best solution to the problem ? It's hard to give a definite answer to this question.
However, from many problems which can be solved by greedy algorithm, it is generally found that this kind of problem has 2 important properties: Greedy choice property and optimal substructure property.
1, greedy choice nature
The so-called greedy choice property refers to the overall optimal solution of the problem can be achieved by a series of local optimal selection, that is, greedy choice. This is the first basic factor that the greedy algorithm is feasible, and it is also the main difference between greedy algorithm and dynamic programming algorithm.
The dynamic programming algorithm usually solve the sub-problems in the bottom-up way, while the greedy algorithm usually takes the top-down approach, and makes successive greedy choices in an iterative way, simplifying the problem to a smaller sub-problem for each greedy choice.
For a specific problem, to determine whether it has a greedy choice nature, must prove that each step of the greedy choice ultimately leads to the overall optimal solution of the problem.
2. Optimal substructure Properties
When the optimal solution of a problem contains the optimal solution of its sub-problem, it is said that this problem has the optimal substructure property. The optimal substructure property of the problem is the key feature that can be solved by the dynamic programming algorithm or greedy algorithm.
3. The difference between greedy algorithm and dynamic programming algorithm
The greedy algorithm and the dynamic programming algorithm all require the problem to have the optimal substructure property, which is one common point of the 2 class algorithm. However, for the problem with the optimal substructure, the greedy algorithm or the dynamic programming algorithm should be used to solve it. Is it possible to solve problems by using dynamic programming algorithms ? The following studies 2 classical combinatorial optimization problems, and illustrates the main difference between greedy algorithm and dynamic programming algorithm.
0-1 knapsack problem:
Given n kinds of items and a backpack. the weight of item I is Wi, its value is Vi, the capacity of the backpack is C. How do you choose which items are loaded into your backpack so that the total value of the items loaded into your backpack is greatest ?
When selecting items for backpack, there are only 2 options for each item I put in the backpack or not in the backpack. Item I cannot be loaded into the backpack multiple times, nor can I only load part of the item i.
Knapsack problem:
Similar to the 0-1 knapsack problem, the difference is that when you select item i into the backpack, you can select part of the item I, and not necessarily all loaded into the backpack,1 <= i <= N.
These 2 kinds of problems have the optimal substructure property, very similar, but knapsack problem can be solved by greedy algorithm, and 0-1 knapsack problem can't be solved by greedy algorithm.
The basic steps of solving knapsack problem with greedy algorithm:
First calculate the value of the unit weight of each item Vi/wi, and then, according to the greedy selection strategy, will be as many units of the highest value of the items loaded into the backpack. If you put all this stuff into your backpack, and the total weight in your backpack doesn't exceed C, choose items with a high weight value and pack as many as you can. Follow this strategy until the backpack fills up.
Pseudo code:
void knapsack (int n,float m,float v[],float w[],float x[])
{
Sort (N,V,W);
int i;
for (i = 1; I <= n; i++)
X[i] = 0;
float c=m;
for (i=1;i<=n;i++) {
if (W[i] > C) break;
X[i]=1;
C-=w[i];
}
if (i <= N)
X[i]=c/w[i];
}
The main computational time of the algorithm knapsack is to sort items from large to small according to their unit weight value. Therefore, the computation time bounds of the algorithm are O (nlogn).
In order to prove the correctness of the algorithm, it is necessary to prove that knapsack problem has greedy choice property.
For the 0-1 knapsack problem, the greedy choice cannot get the best solution because in this case, it can not guarantee that the backpack will eventually fill up, part of the empty backpack space to reduce the value of each kilogram of backpack space. In fact, when considering the 0-1 knapsack problem, you should compare the choice of the item with the final plan that resulted from not selecting the item and then making the best choice. Thus, many overlapping sub-problems are derived. This is another important feature of the problem that can be solved by dynamic programming algorithms. In fact, the dynamic programming algorithm can effectively solve the problem of 0-1 knapsack.
Question two, Huffman Code
Huffman coding is a very effective coding method widely used in data file compression. The compression rate is usually between 20%~ 90%. Huffman coding algorithm uses the frequency table of characters appearing in the file to establish an optimal representation of each character by 0 and 1 strings.
For shorter characters with high frequency, the characters with lower frequency are encoded long, which can greatly shorten the total code length.
abcdef
Frequency (Thousand)95
Fixed length code 001010011101
Variable length code 010111111011100
Fixed length code:
(45+13+12+16+9+5) = thousand
Variable length code:
1*45+3*13+3*12+3*16+4*9+4*5 = 224 thousand
1. Prefix code
A 0,1 string is specified for each character as its code, and the code that requires either character is not prefixed with any other character code. This encoding is called a prefix code.
The encoding prefix nature can make the decoding method very simple.
The two fork tree that represents the optimal prefix code is always a completely binary tree, that is, any node in the tree has 2 son nodes.
F (c) indicates the probability that the character C appears,DT (c) indicates the code length of C
The average code length is defined as:
The Prefix code encoding scheme, which makes the average code up to the minimum, is called the optimal prefix code for the given coded character set C.
2. Construct Huffman Code
Huffman proposed to construct the optimal prefix code greedy algorithm, the resulting coding scheme is called Huffman coding.
The Huffman algorithm constructs a two-fork tree T which represents the optimal prefix code in a bottom-up way .
Algorithm to | C| a leaf node start, execute | c|-1 times the "merge " operation produces the final required tree T.
The priority queue Q with the F as the key value is used in the greedy selection to effectively determine the 2 tree with the minimum frequency that the algorithm is currently merging. Once the 2 trees with the minimum frequency are merged, a new tree is generated, with a frequency of the sum of the frequencies of the combined 2 trees, and the new tree is inserted into the priority queue Q. after a N-1 merger, only one tree is left in the priority queue, which is the requested tree T.
The algorithm huffmantree the priority queue Q with the minimum heap . An O (n) computation time is required to initialize the priority queue , because the removemin and put operations of the minimum heap require O (logn) time, anda total of O (NLOGN) is required to combine N 1 times. Therefore, the calculation time of the Huffman algorithm of n characters is O (NLOGN).
3. The correctness of Huffman algorithm
To prove the correctness of Huffman algorithm, we can prove that the optimal prefix code problem has the greedy choice property and the optimal substructure property.
(1) Greedy choice nature
(2) Optimal substructure properties
Realize:
Code
Problem three, single source maximum path
Given the weighted graph G = (v,e), the right of each edge is a nonnegative real number. In addition, a vertex in V is given, called the source. Now you want to calculate the shortest path length from the source to all the other vertices. The length of the road here refers to the sum of the right side of the road. This problem is often referred to as the single source shortest path problem.
1. Basic idea of algorithm
Dijkstra algorithm is a greedy algorithm for Jianhanyuan shortest path problem.
The basic idea is to set up the vertex set s and continue to make greedy choices to augment this set. A vertex belongs to the set s when and only if the shortest path length from the source to the vertex is known.
Initially,s contains only the source. Set U is a vertex of G, the path from source to U and only through the vertices of s in the middle is called a special path from source to u, and the shortest special path length corresponding to each vertex is recorded with array Dist. The Dijkstra algorithm removes the vertex u with the shortest special path length from the V-s each time , adds u to s, and makes the necessary modifications to the array dist. Once s contains all the vertices in V, theDist records the shortest path length from source to all other vertices.
For example, for a forward graph in a pair, the process of applying the Dijkstra algorithm to calculate the shortest path from source vertex 1 to other vertices is listed in the following table.
the iterative process of the Dijkstra algorithm:
Iteration Sudist[2]dist[3]dist[4]dist[5]
Initial {1}- maxint
1{2 }
2{1,2,4}4
3{1,2,4,3}3
4{1,2,4,3,5}5
2. Correctness and computational complexity of the algorithm
(1) Greedy choice nature
(2) Optimal substructure properties
(3) Computational complexity
For weighted graphs with n vertices and e edges, if the graph is represented with a weighted adjacency matrix, then the main loop body of the Dijkstra algorithm needs O (n) time. This loop requires an O (n) time to perform the n-1, so the loop is completed. The remainder of the algorithm does not take longer than O (n^2).
Greedy selection algorithm