Previously, we introduced how to use dynamic planning to solve some optimization problems. However, for some optimization problems, using dynamic planning is "Anti-Spam", which can be solved simply and effectively. Greedy algorithms are one of them. Greedy algorithms make the selection seem to be the best at present, and expect to produce a global optimal solution through the local optimal selection.
I. Selection of activities
[Problem] schedule several competing activities: Activity Set S = {A1, A2 ,..., an}, all of which require the use of a public resource (such as a classroom) in an exclusive manner, each activity Ai has a start time Si and end time Fi, and 0 ≤ Si <fi <∞. Once selected, the active AI occupies the half-open time range [Si, FI). If the range [Si, FI) and [SJ fj) they do not overlap with each other (SI ≥ FJ or SJ ≥ FI ).Compatible.
[Objective] To find the largest (most active) set of mutually compatible activities.
1. Dynamic Planning solution:
A. Optimal sub-structure:
SIJ is a subset of activities in S. Each activity starts after activity AI and ends before activity AJ starts. They are compatible with AI and AJ, and are also compatible with any activities not later than AI and not earlier than AJ.
Assume that the activity is sorted in a monotonically ascending order of the End Time: F0 ≤ F1 ≤ F2 ≤... ≤ FN <FN + 1, where f0 = 0 and Sn + 1 = ∞.
Apparently, when I is ≥j, SIJ = ?.
The sub-problem space is to select the maximum compatible activity subset from SIJ, where 0 ≤ I <j ≤ n + 1
B. recursively define the optimal solution
Consider a non-empty subproblem SIJ, and assume that its solution contains an active AK, of which fi ≤ SK <FK ≤ SJ, you can use the active AK to generate two subproblems: Sik and skj.
Assuming that the optimal solution of sij aij contains the active AK, it is included in the SIJ optimal solution of the sik aik and the solution of the skj akj must be the best.
So: AIJ = AIK token {AK} Then akj
Set C [I, j] to the number of activities in the maximum compatible subset of SIJ. When SIJ = ?, C [I, j] = 0; when I is ≥j. c [I, j] = 0; if the AK is used in the maximum compatibility subset of SIJ, the maximum compatible subset of Sik and skj is also used, there is a recursion: C [I, j] = C [I, K] + C [K, J] + 1.
2. Greedy Algorithm: Converting dynamic planning solution into greedy Solution
[Theorem] for any non-empty subproblem SIJ, set AM to the activity with the earliest End Time in SIJ: fm = min {FK: AK ε SIJ}. So:
1) activity am is used in a maximum compatible activity subset of SIJ;
2) The sub-problem SIM is empty, so selecting am will make the sub-problem smj the only sub-problem that may not be empty.
From the theorem above, we can see that we only need to consider one subproblem (the other subproblem must be empty). When solving the subproblem SIJ, we only need to consider one option: the activity with the earliest End Time in SIJ can solve each subproblem from top to bottom: To solve the subproblem SIJ, select the activity am with the earliest End Time in SIJ, add the activity set in the optimal solution of smj to the solution of SIJ.
A. Recursive greedy algorithm:
Recursive-Activity-Selector(s, f, i, j)1 m<--i+12 while m < j and sm < fi3 do m<--m+14 if m < j5 then return {am}∪Recursive-Activity-Selector(s, f, m, j)6 else return nilB. Iterative greedy algorithm: it is easy to find that the above recursive algorithm is a tail recursion and can be easily converted into an iterative algorithm.
Greedy-activity-selector (S, F) 1 n <-- length [s] 2 A <-- {A1} 3 I <-- 14 for m <-- 2 to N5 do if Sm> = Fi // activity and select the previous compatible with 6 then a <-- a minutes {Am} 7 I <-- M8 return
Ii. Basic Content of greedy Policy
Principle: greedy algorithms give the optimal solution to a problem by making a series of choices. Make the best choice for every decision point in the algorithm at that time.
1. In the previous section, we developed a greedy algorithm through the following steps:
A) determine the optimal sub-structure of the problem;
B) Design a recursive solution;
C) prove that, at any stage of recursion, one of the optimal options is always greedy. Therefore, it is always safe to make greedy choices;
D) prove that only one subproblem is not empty by making greedy choices;
E) Design a recursive algorithm to implement greedy policies;
F) convert recursive algorithms into iterative algorithms.
2. the above steps are too cumbersome and can be simplified:
A) transform the optimization problem into such a problem, that is, first make a choice, and then solve the remaining sub-problem;
B) prove that there is always an optimal solution for the original problem that is obtained through greedy selection, which indicates that greedy selection is safe;
C) It indicates that the greedy choice satisfies the optimal sub-structure. Therefore, we can combine the optimal solution of the sub-problem with our greedy choice to obtain an optimal solution of the original problem.
3. Greedy Algorithm usage conditions: greedy selection and optimal sub-structure are two key features. If we can prove that the problem has these properties, we can design a greedy algorithm.
A,Greedy choice: A global optimal solution can be achieved through local optimum (Greedy) selection.
This is because the greedy algorithm is different from dynamic planning. In the dynamic planning process, each step makes a choice. These choices depend on the solution of the subproblem. First, the subproblem is solved and then the choice is made! We must prove that the greedy choice made at each step will eventually produce a global optimal solution. In the proof, we first examine a global optimal solution, and then prove that the solution can be modified to make it adopt greedy selection, which is still the optimal solution.
Greedy selection is usually selected by a value: a fixed priority; a changed priority.
B,Optimal sub-structure: For a problem, if an optimal solution contains the optimal solution of its subproblems, the problem is called an optimal sub-structure.
Comparison:
Iii. Bellman-Ford Algorithm
[Problem] a weighted directed graph G = (V, E) is given. The weighted function W: e → R is the ing from the edge to the real number, calculate the single-source shortest path (sum of weights) from the given point S to all the fixed points ).
1. Optimal sub-structure of the shortest path: the sub-path of the shortest path is the shortest path.
2. Negative Edge Weight: if graph G = (V, E) does not contain a negative weight loop reachable from the source S, the shortest path permission is defined as delta (S, V. You can see laterDijkstra algorithm assumes that all edge values are not negative,The bellman-Ford algorithm allows negative weight edges in the input graph.
3. Loop: the shortest path cannot contain both positive and negative weights. It can contain 0 weights, but is unnecessary.
4. Representation of the shortest path: A precursor subgraph. When the algorithm ends, G π is the shortest path tree. The shortest path is not unique, so the shortest path tree is the same.
5. relaxation technology: a property D [v] is set for each vertex v, which is used to describe the upper bound of the weight on the shortest path from the Source Vertex s to v.Shortest Path Estimation.
Initialize Shortest Path estimation:
Initialize-Single-Source(G, s)1 for each vertex v in V[G]2 do d[v]<--INF3 Pi[v]<--nil4 d[s]<--0
When a side (u, v) is relaxed, test whether u can be used to improve the shortest path to V found so far. If yes, then, update d [v] and π [v].
Relax(u, v, w)1 if d[v] > d[u] + w(u, v)2 then d[v]<--d[u] + w(u, v)3 <span style="white-space:pre"></span>Pi[v]<--u
Relaxation is the only way to change the shortest path and the precursor. The algorithms in this chapter differ in the number of relaxation operations on each edge and the order of the relaxation operations on the edge. In the Dijkstra algorithm and the shortest path algorithm for Directed Acyclic graphs, perform a relaxation operation on each edge. In the Bellman-Ford algorithm, multiple relaxation operations are performed on each edge.
Shortest Path and relaxed nature:
A. Triangular inequality: For any side (u, v) ε E, Delta (S, v) <= delta (S, U) + W (U. V );
B. Upper Bound Properties: For any vertex v in V, d [v]> = delta (S, V), and once d [v] reaches delta (S, V) the value will not change.
C. No path: If there is no path from S to V, d [v] = delta (S, v) = inf
D. Convergence: If s --> u --> V is the shortest path of a certain U in the graph G, and the relaxation side (u, v) at any time prior to d [u] = delta (S, U), then after the operation, d [v] = delta (S, v) always exists ).
E,Path relaxation: If P = <v0, V1 ,..., VK> is the shortest path from S = V0 to VK, and the P side follows (v0, V1), (V1, V2 ),..., (Vk-1, VK) the order of relaxation, then d [VK] = delta (S, VK ). The persistence of this property is not affected by other relaxation operations, even if they are mixed with the relaxation operations on the edge p.
6. Bellman-Ford algorithm: Generally (Negative Edge Weight) To solve the single-source shortest path problem.
Bellman-Ford(G, w, s)1 Initialize-Single-Source(G, s)2 for i <--1 to |V[G]|-13 do for each edge (u, v) in E[G]4 do Relax(u, v, w)5 for each edge (u, v) in E[G]6 do if d[v] > d[u] + w(u, v)7 then return False8 return True
The total running time is O (VE ).
Iv. Dijkstra Algorithm
1. Dijkstra algorithm solves the single-source shortest path problem on Directed Graph G = (V, E), but requiresNon-negative weight.
A. Assume that w (u, v) and E are greater than or equal to 0 for each edge;
B. The weight of the shortest path from the Source Vertex s to the vertex s in the set has been determined.
C. The algorithm repeatedly selects the vertex u in V-S with the shortest path estimation, and adds u to S to relax all the edges of U.
D,Q is the smallest priority queue of vertices, And the sorting keyword is the vertex's D value..
Dijkstra(G, w, s)1 Initialize-Single-Source(G, s)2 S<--Nil3 Q<--V[G]4 while Q != nil5 do u<--Extract-Min(Q)6 S<--S ∪ {u}7 for each vertex v ∈ adj[u]8 do Relax(u, v, w)Because the Dijkstra algorithm always selects the "lightest" or "nearest" vertex in the V-S and inserts it into the set S, we say it uses a greedy policy.
Every time a vertex u is inserted into the set S, d [u] = delta (S, U) exists ).
2. Theorem: the weighted directed graph G = (V, E) is known. The value of the weighted function W is non-negative and the Source Vertex is S. Run the Dijkstra algorithm on the graph. When the algorithm is terminated, all u in V has d [u] = delta (S, U ).
3. Run Time Analysis of Dijkstra algorithm:
A. Three priority queue operations are called: insert (3rd rows) | v | times, EXTRACT-MIN (5th rows) | v | times, decrease-Key (in relax of the 8th line call) has a total of | E | iterations in all for loops.
B. The algorithm running time depends on the specific implementation of the Minimum priority queue: simply store d [v] into the V Entry of an array. The insert and decrease-key operations are O (1) time, EXTRACT-MIN operation is O (v) time. The total time is O (V ^ 2 + E + V) = O (V ^ 2 ).
Select queue operations with different priorities:
Time = N x (t (insert) + T (extract-min) + m x T (decrease-Key), where (| v | = n, | E | = m)
V. Theoretical Basis of greedy algorithms: quasi-array
Some of the problems that can be solved by greedy methods can be solved by generic "quasi-arrays, although arrays do not cover all the situations that the greedy method applies (for example, the issue of activity selection and the issue of Heman encoding), they cover many practical scenarios and are growing rapidly, and is covering more applications.
1. Arrays:
M = (S ,?) :
1) S isFinite non-empty set;
2 )? Is a non-empty subset family of S, which is called an independent subset of S? And? B, then ?. What do we say? YesGeneticIf it meets this nature. (Empty set? Required? )
3) if ?, B ?, And | A | <| B |, there is an element x in B-A that causes a into {x} in ?. We call m satisfiedExchange nature.
2. Greedy Algorithm of weighted pseudo-array:
Greedy(M, w)1 A<--nil2 sort S[M] into monotonically decreasing order by weight w3 for each x in S[M], taken in monotonically decreasing order by weight w4 do if A∪{x}∈l[M]5 then A<--A∪{x}6 return AGreedy running time: N = | S |
1) The time of greedy's sorting phase is O (n lgn );
2) in Row 3, each element in S is executed once, n times in total;
3) check whether a pair {x} is independent in each execution of Row 3;
4) if the time for each check is O (f (n), the running time of the entire algorithm is O (n lg n + NF (n )).
Many problems that are suitable to use greedy methods to obtain the optimal solution can be attributed to the weighted pseudo-array M = (S ,?) To find an independent subset of a? With the maximum weight of w (? .