Docsity

Huffman Coding Algorithm: Minimizing Binary Code Length, Assignments of Algorithms and Programming

Toggle sidebar
bg1
Chapter III
Greedy Algorithms
We consider algorithms for optimization problems that make greedy choices according to
some local criteria. The resulting algorithms are often simple and fast. However, they
rarely give an optimal solution. We consider several examples in which a greedy approach
gives an optimal solution and also several in which it does not. In the latter case, we are
still interested in how good the solution obtained is.
III.1 Huffman Codes
We consider the problem of generating a binary code for a set of characters Cwith fre-
quencies f:C→N. Specifically, we want to determine for each c∈Ca corresponding
binary string, called its codeword and denoted w(c), such that a string of characters in C,
is encoded by simply concatenating the codewords of its characters (preserving the order
of the characters in the message of course). Let length(x) denote the number of bits in x.
Suppose cappears f(c) times in the string, then total length of the encoded message is
(overloading the notation)
length(C, f ) = X
c∈C
f(c)·length(w(c))
The goal is to determine wso that length(C, f ) is minimized.
We concentrate on prefix codes, that is, no w(x) is a prefix of another w(y). Under
this constraint, a codeword assignment can be viewed as a binary tree (0 to the left, 1 to
the right) with the characters as leaf labels. We can assume the tree is full (every internal
node has two children), as otherwise the node with a single child could be bypassed and
length(w(M)) would be improved.
In summary, we want to find a tree Tthat minimizes
B(T, C , f) = X
c∈C
f(c)·depth(c, T ),
where depth(c, T ) denotes the depth in Tof the leaf labeled with c.
To solve this optimization problem, we first identify a way to reduce the problem to a
smaller instance. Consider an optimal tree Tfor C, f . A possibility is to observe that the
left subtree and the right subtrees should be optimal for the subset of characters in those
III.1
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Huffman Coding Algorithm: Minimizing Binary Code Length and more Assignments Algorithms and Programming in PDF only on Docsity!

Chapter III

Greedy Algorithms

We consider algorithms for optimization problems that make greedy choices according to some local criteria. The resulting algorithms are often simple and fast. However, they rarely give an optimal solution. We consider several examples in which a greedy approach gives an optimal solution and also several in which it does not. In the latter case, we are still interested in how good the solution obtained is.

III.1 Huffman Codes

We consider the problem of generating a binary code for a set of characters C with fre- quencies f : C → N. Specifically, we want to determine for each c ∈ C a corresponding binary string, called its codeword and denoted w(c), such that a string of characters in C, is encoded by simply concatenating the codewords of its characters (preserving the order of the characters in the message of course). Let length(x) denote the number of bits in x. Suppose c appears f (c) times in the string, then total length of the encoded message is (overloading the notation)

length(C, f ) =

c∈C

f (c) · length(w(c))

The goal is to determine w so that length(C, f ) is minimized.

We concentrate on prefix codes, that is, no w(x) is a prefix of another w(y). Under this constraint, a codeword assignment can be viewed as a binary tree (0 to the left, 1 to the right) with the characters as leaf labels. We can assume the tree is full (every internal node has two children), as otherwise the node with a single child could be bypassed and length(w(M)) would be improved.

In summary, we want to find a tree T that minimizes

B(T, C, f ) =

c∈C

f (c) · depth(c, T ),

where depth(c, T ) denotes the depth in T of the leaf labeled with c.

To solve this optimization problem, we first identify a way to reduce the problem to a smaller instance. Consider an optimal tree T for C, f. A possibility is to observe that the left subtree and the right subtrees should be optimal for the subset of characters in those

subtrees. A dynamic programming solution would have to look at all the possible ways of splitting C into two subsets, and so in the end it would have to construct a table of optimal trees for all the possible subsets of C. This is quite inefficient.

An alternative is to look at two siblings x, y in T , remove them and label the new leaf (the old parent of x and y) with a new character z. Let C′^ = C − {x, y} ∪ {z} be a new alphabet, let f ′(z) = f (x) + f (y) and f ′(c) = f (c) for c ∈ C′^ and c 6 = z be their frequencies, and let T ′^ be the modified tree.

T’

x y

z

T

Claim 1. T ′^ is optimal for C′, f ′.

Proof. First note that

B(T, C, f ) = B(T ′, C′, f ′) + f (x) + f (y).

Suppose T ′^ is not optimal for C′, f ′, and let T ′′^ be an optimal tree for C′, f ′. That is, B(T ′′, C′, f ′) < B(T ′, C′, f ′). In T ′′^ substitute z with a node with two children x and y; let T ′′′^ be the resulting tree.

T’’’

x y

z

T’’

Similarly as above,

B(T ′′′, C, f ) = B(T ′′, C′, f ′) + f (x) + f (y).

Thus,

B(T ′′′, C, f ) = B(T ′′, C′, f ′) + f (x) + f (y) < B(T ′, C′, f ′) + f (x) + f (y) = B(T, C, f ),

which is a contradiction since T was supposed to be optimal for C, f.

This leads then to an approach using dynamic programming: for all possible pairs x, y substitute them with a z with frequency f (x) + f (y) and solve the reduced problem; the solution is the best over all the pairs. This approach is also not very good as there will be again too many different subproblems that will need to be solved. Here being greedy comes to the rescue: we can take two characters with lowest frequencies as x and y. There is no need to try all pairs.

How small can length(C, f ) be?

Let F =

c∈C f^ (c).^ The following bounds depend on the ratio^ f^ (c)/F^ ; if the source is random, this may be interpreted as the probability of c appearing in the string.

Lemma 3.

length(C, f ) ≥

c∈C

f (c) · log(F/f (c)).

Proof. In other words, we want to show that for any tree T for C, B(T, C, f ) is larger than or equal to the term on the right hand side. The proof is by induction on the size of C. It is clearly true for |C| = 1 (then B(T, C, f ) is zero). Now, for |C| > 1 let T be any tree for C. Let Tl and Tr be the left and right subtrees of T and let Cl and Cr be the subsets of C corresponding to Tl and Tr. Also let Fl and Fr be the respective frequency totals (so F = Fl + Fr). Using the induction hypothesis:

B(T, C, f ) =

c∈C

f (c) · depth(c, T )

c∈Cl

f (c) · (depth(c, Tl) + 1) +

c∈Cr

f (c) · (depth(c, Tr) + 1)

c∈Cl

f (c) · depth(c, Tl) +

c∈Cr

f (c) · depth(c, Tr) + F

c∈Cl

f (c) · log(Fl/f (c)) +

c∈Cr

f (c) · log(Fr/f (c)) + F

The last term on the right hand side is greater than

c∈C f^ (c)^ ·^ log(F/f^ (c)) if ∑

c∈Cl

f (c) · log(Fl/f (c)) +

c∈Cr

f (c) · log(Fr/f (c)) + F −

c∈C

f (c) · log(F/f (c)) ≥ 0 ,

which we verify next to complete the proof. The left side in this inequality simplifies to

Fl log Fl + Fr log Fr + F − F log F ;

since Fl log Fl + Fr log Fr is minimized when Fl = Fr = F/2 (check by computing the derivative) and achieves the value F log(F/2) = F log F − F , the inequality that we wanted to vverify holds. This completes the proof.

What value of length(C, f ) can actually be achieved?

Our greedy algorithm certainly obtains a T that corresponds to the optimal value of length(C, f ). But how close is that to the lower bound above?

III.2 Minimum Spanning Tree

We consider the problem of finding a spanning tree of a minimum total weight in weighted undirected graphs. Let G = (V, E) be an undirected graph and let w : E → R be a weight function on the reals (it is not restricted to be positive but you may think it is

initially). For technical reason we assume though that all weights are different; there is no loss of generality in assuming this, this can be enforced using, for example, lexicographical ordering.^1 Recall that a tree is a connected acyclic graph.^2 A tree is spanning in graph G = (V, E) if its vertex set is V (it includes all vertices). An important observation that we use is the following:

Observation 5. Let T be a spanning tree of G = (V, E) and let e be an edge not in T , then Te = T ∪ {e}^3 has a unique cycle C, and removing any edge in C from Te results in a spanning tree of G.

The weight of a subgraph G′^ of G is the sum of weights of edges in G′. We are interested in finding a spanning tree of G with minimum weight over all spanning trees of G. We call this a minimum spanning tree (MST), though minimum weight spanning tree would be more appropriate.

A forest is an acyclic graph; hence a collection of trees (each connected component is a tree). We consider a generic MST algorithm that maintains a spanning forest F and adds edges incrementally (starting with a forest without edges). The invariant is that F is a subgraph of an MST (the algorithm and its correctness actually show that there is a unique MST).

Definition. An edge not in the forest is said to be useless if both of its vertices are in the same connected component of F. An edge that is not useless is said to be safe for a

(^1) Assume that the vertices are indexed from 1 to n: V = {v 1 , v 2 ,... , vn}. So each edge is a pair {vi, vj }.

Let w : E → R be a weight assignment possibly with equal weights. We define a weight assignment w′^ : E → R that has no equal weights. For e = {vi, vj } with i < j, let

w′(e) = w(e) + i ·  + j · ^2 ,

where  > 0 is an arbitrarily small number. We claim that given w, there is an  0 > 0, such that for any  with 0 <  <  0 , no two weights w′^ are equal. It follows that the ordering is independent from the choice of . Furthermore, the ordering can be evaluated based only on the indices without the specific computation of w′^ with a particular . More precisely, the claim is:

Claim 4. There is  0 > 0 such that for any  with 0 <  <  0 and any edges e 1 = {i 1 , j 1 } and e 2 = {i 2 , j 2 } with i 1 < j 1 and i 2 < j 2 , w′(e 1 ) < w′(e 2 ) iff either:

(i) w(e 1 ) < w(e 2 ), or (ii) w(e 1 ) = w(e 2 ) and i 1 < i 2 , or (iii) w(e 1 ) = w(e 2 ), i 1 = i 2 and j 1 < j 2.

Proof. Let ∆ be the minimum of 1 and of |w(e)−w(e′)| over all e and e′^ with w(e) 6 = w(e′), let  0 = ∆/ 2 n^2 , and let  <  0. If w(e 1 ) < w(e 2 ) then w′(e 1 ) < w′(e 2 ) because |(i 1 −i 2 )+(j 1 −j 2 )^2 | is strictly smaller than ∆. If w(e 1 ) = w(e 2 ) and i 1 < i 2 then w′(e 1 ) < w′(e 2 ) because |(j 1 − j 2 )^2 | is smaller than ∆^2 / 4 n^3 which is smaller than ∆/ 2 n^2 (recall ∆ ≤ 1), which is the minimum possible value of |(i 1 − i 2 )|. If w(e 1 ) = w(e 2 ), i 1 = i 2 and j 1 < j 2 then clearly w′(e 1 ) < w′(e 2 ).

The ordering of the indices that appear in (ii) and (iii) is called lexicographic ordering. (^2) A graph is connected if any two verices are connected by a path in the graph. It is acyclic if it contains

no cycle. The following are equivalent characterizations: A tree is (a) a connected acyclic graph; (b) a connected graph with at most |V | − 1 edges; (c) a minimal connected graph (it is connected and removing any edge makes it disconnected); (d) an acyclic graph with at least |V |-1 edges; (e) a maximal acyclic graph (it is acyclic and adding any edge makes creates a cycle). (^3) Frequently, we abuse notation to make writing easier. Strictly, T is a pair (V, F ) of vertices and edges

and we are adding e to the set of edges, but that’s too messy to write, so T ∪ {e} will do.

MST-Jarnik-Initialization (V, E, s) Q←MakeHeap for each v ∈ V − {s} if {v, s} ∈ E edge(v)←{v, s} key(v)←w({v, s}) else edge(v)←Null key(v)←∞ HeapInsert(Q, v)

The running time is determined by the DecreaseKey operation. Using normal heaps, this takes time O(log n) and so the total running time is O(|E| log |V |) time. However, there are heaps that support this operation in amortized time O(1) (we’ll se later what that means) and so the total time is O(|E| + |V | log |V |) (ExtractMin still needs time O(log n)).

Algorithm 2 (Kruskal). This algorithm sorts the edges in increasing weight order and considers them in that order; if the edge under consideration is safe, add it to F. To check that an edge is safe, it suffices to check that is not useless (since the edges are considered in increasing weight order it is not possible that the algorithm will consider an edge connecting two different components and which is not safe for either of the components – since the safe edge of a component has smallest weight among those out of the component). To implement this algorithm, we use a so called union-find data structure: it maintains a set of disjoint sets, and supports three operations: MakeSet(u) makes a new set that contains u, Find(u) returns the identifier of the set that contains u, and Union(u, v) unions the two sets that contain u and v. The initialization is as follows:

MST-Kruskal (V, E) sort E in increasing order of w F ←∅ for each v ∈ V MakeSet (u) for i = 1 to |E| {u, v}←i-th lightest edge in E if Find(u) 6 = Find(v) Union(u, v) add {u, v} to F

The running time is dominated by the sorting and so is O(|E| log |V |).

III.3 Knapsack Problem

Pending ...

III.4 Set Cover

We now consider another problem for which no “efficient” algorithm is known. We are given a universe set U = {x 1 , x 2 ,... , xn} and a collection S of subsets of U together with a cost function c : C → Q. The problem is to find a cover C ⊆ S of minimum cost for S. More precisely, we want C ⊆ S such that

S∈C S^ =^ U^ and^ c(C) =^

S∈C is minimum. With different possible variations, this problem appears frequently in applications. (As a simple example, think of U as a set of persons, and the sets in S as different clubs each with a subgroup of persons belonging to it – a person can belong to several clubs – and each one with a correponding cost to support it. We want to choose a set of clubs with a minimum total cost and which would cover all the persons.)

A “natural” approach ito find a cover is to greedily take sets in S that cover elements in U not yet covered as “cost-effectively” as possible. The following pseudocode makes this precise.

Greedy-Set-Cover (U, S) C←∅; C←∅ while C 6 = U do find S ∈ S − C that minimizes (^) |Sc(−SC)| C←C ∪ S; C←C ∪ {S} return C

In each iteration, we choose the set S not yet selected that minimizes the ratio of its cost c(S) to the number |S − C| of new elements that it would cover.

Let OPT and GREEDY be the cost of an optimal solution and the cost of a greedy solution respectively. We will argue that

GREEDY OPT

≤ Hn

where Hn = Θ(log n) is the n-th harmonic number.

When a set S is selected, let us give an order to the new elements covered – those in S − C – so that we can speak of the list of all the elements in the order in which they are covered by the greedy algorithm. Say this order is

x 1 , x 2 , x 3 ,... , xn− 1 , xn.

Also, for xi ∈ S − C, let price(xi) = c(S)/|S − C|. Intuitively, this is the price that we are “paying” for this element (on the average) since we paid c(S) for |S − C| elements. Clearly

GREEDY =

∑^ k

j=

c(Si) =

∑^ n

i=

price(xi),

where S 1 , S 2 ,... , Sk are the sets taken by the greedy algorithm. Now consider when xi is covered by a corresponding chosen set Sj. Clearly prior to this |U − C| ≥ n − i + 1 since xi, xi+1,... , xn had not yet been covered. Also, we know that –even at this later stage– there was a cover Cj for the remaining elements U − C of cost at most OPT (there was