0% found this document useful (0 votes)
3 views18 pages

7 - M4C Trees Cây B7

The document outlines a mathematics course focused on computing, taught by Dr. Hoàng Anh, covering topics such as set theory, formal logic, number theory, relations, graph theory, and probability. It includes a detailed section on trees, defining them as connected undirected graphs without cycles, and discusses their properties, applications, and the concept of spanning trees. The course aims to provide foundational knowledge in mathematical concepts relevant to computer science and information technology.

Uploaded by

lethanhloi0603
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

7 - M4C Trees Cây B7

The document outlines a mathematics course focused on computing, taught by Dr. Hoàng Anh, covering topics such as set theory, formal logic, number theory, relations, graph theory, and probability. It includes a detailed section on trees, defining them as connected undirected graphs without cycles, and discusses their properties, applications, and the concept of spanning trees. The course aims to provide foundational knowledge in mathematical concepts relevant to computer science and information technology.

Uploaded by

lethanhloi0603
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Toán dành cho tin học

Mathematics for Computing

Giảng viên: TS. Hoàng Anh


Khoa CNTT-KD (BIT_CTD)
[email protected]

Nội dung
˗ Giới thiệu + Tập hợp _ Set Theory (Buổi 1)
˗ Logic_Formal Logic và Chứng minh (Buổi 2)

˗ Lý thuyết số _ Number theory và Mã hóa (Buổi 3)


˗ Quan hệ _ Relations (Buổi 4)

˗ Chuyên đề (Buổi 5)/LMS_Solution


˗ Lý thuyết Đồ thị _ Graph theory (Buổi 6)
˗ Cây và Cây khung (Buổi 7)

˗ Đại số Boole (Buổi 8)


˗ Xác suất (Buổi 9)
Cây và Cây khung
Chương 11. Cây/ Trees
11.1 Giới thiệu cây
11.2 Ứng dụng cây
11.3 Duyệt cây
11.4 Cây khung
11.5 Cây khung nhỏ nhất

11.1 Giới thiệu cây

u Khái niệm: Cây là đồ thị vô hướng liên thông


không có chu trình
u Arthur Cayley, 1857: khi ông sử dụng chúng để
đếm một số dạng cấu trúc phân tử của các hợp
chất hóa học trong hóa học hữu cơ
u Cây được sử dụng rộng rãi trong nhiều lĩnh vực,
đặc biệt trong tin học (xây dựng các thuật toán
tổ chức các thư mục, các thuật toán cất giữ,
truyền dữ liệu, và tìm kiếm,…)
11T Cây/ Trees
MHIA017-Rosen-v5.cls May 13, 2011 10:27

u A tree is a connected undirected graph with no simple circuits.


1 / Trees

a b a b a b a b

d c
c d
c d c d

e f e f e f e f

G1 G2Not a tree G3 G4
Not a tree
FIGUREA
2 tree HasThat
Examples of Trees and Graphs a cycle
Are Not Trees. Not connected

INITION 1 A tree is a connected undirected graph with no simple circuits.

Because a tree cannot have a simple circuit, a tree cannot contain multiple edges or loops.
Therefore any tree must be a simple graph.
XAMPLE 1 Which of the graphs shown in Figure 2 are trees?

Solution: G1 and G2 are trees, because both are connected graphs with no simple circuits. G3 is
not a tree because e, b, a, d, e is a simple circuit in this graph. Finally, G4 is not a tree because
it is not connected.

Cây và các tính chất của cây


Any connected graph that contains no simple circuits is a tree. What about graphs containing
no simple circuits that are not necessarily connected? These graphs are called forests and have
the property that each of their connected components is a tree. Figure 3 displays a forest.
u Trees
Đồ thịare often defined as undirected graphs with the property that there is a unique simple
không có chu trình được gọi là RỪNG
path between every pair of vertices. Theorem 1 shows that this alternative definition is equivalent
to our definition.
u RỪNG là đồ thị mà mỗi thành phần liên thông của nó là một cây

HEOREM 1 An undirected graph is a tree if and only if there is a unique simple path between any two of
its vertices.

This is one graph with three connected components.

FIGURE 3 Example of a Forest.


tree T . We usually draw a rooted tree with its root at the top of the graph. The arrows indicating
748 11 / Trees
the directions of the edges in a rooted tree can be omitted, because the choice of root determines
the directions of the edges.
The terminology for T trees has
a botanical and genealogical origins. Suppose that T is a rooted

tree. If v is a vertex in T other than the root, the parent of v is the unique vertex u such that there
is a directed edge from u to v (the reader should show that such a vertex is unique). When u is
the parent of v, v is called a child of u. Vertices with the same parent are called siblings.
g The
Rooted Trees b g
ancestors of a vertex other than the root are the vertices in the path from the root to this vertex,
f

excluding the vertex itself and including the root (that is, its parent, its parent’s parent, and so
u A rooted tree is a tree in which one vertex has been
on, until the root is reached). The hdescendantsj of a vertex v are those verticesh that have j v as
designated as the root and everyi edge is directed away
c
i
from the root.
T With root a With root c
f g d e k a l m c k l m

d FIGURE 5 Ab Rooted Tree T . a FIGURE 6 The


b c Subtree Rooted at g.
d e
e b
an ancestor. A vertexg of ea rooted tree is called a leaf if it has no children. Vertices that have
a f d
children are called internal vertices. The root is an internal vertex unless it is the only vertex
in the graph, in which case it is a leaf.
c g is the subgraph of the tree consisting
If a is a vertex in a tree, the subtree withf a as its root
of a and its descendants and all edges incident to these descendants.
FIGURE 4 A2 Tree
EXAMPLE In theand Rooted
rooted Treesroot
tree T (with Formed
a) shownby Designating
in Figure 5, find theTwo
parentDifferent Roots.of g, the
of c, the children
siblings of h, all ancestors of e, all descendants of b, all internal vertices, and all leaves. What
is the subtree rooted at g?

Solution: The parent of c is b. The children of g are h, i, and j. The siblings of h are i and j.
The ancestors of e are c, b, and a. The descendants of b are c, d, and e. The internal vertices
are a, b, c, g, h, and j. The leaves are d, e, f , i, k, l, and m. The subtree rooted at g is shown
in Figure 6.


Rooted trees with the property that all of their internal vertices have the same number of
children are used in many different applications. Later in this chapter we will use such trees to
Binary Trees study problems involving searching, sorting, and coding.
u A rooted tree is called an m-ary tree if every internal
DEFINITION
vertex has3no more
A rootedthan
tree ism children.
called an m-ary The
tree if tree
every is called
internal a has no more than m children.
vertex
The tree is called a full m-ary tree if every internal vertex has exactly m children. An m-ary
full m-ary treetree
if with
everym =internal
2 is called avertex has exactly m
binary tree.
children. An m-ary tree with m = 2 is called a binary tree.
EXAMPLE 3 Are the rooted trees in Figure 7 full m-ary trees for some positive integer m?

T1 T2 T3 T4

FIGURE 7 Four Rooted Trees.


P1: 1
CH11-7T Rosen-2311T MHIA017-Rosen-v5.cls May 13, 2011 10:27

Tree as Model
u Trees are used as models in such diverse areas as computer
11.1 Introduction to Trees 751
science, chemistry, geology, botany, and psychology.
President

VP VP VP VP
R&D Marketing Services Finance

Director Director Chief Director


Director AVP AVP Director Director
Software Hardware Field Material
Research Sales Marketing Accounting MIS
Development Development Operations Management

FIGURE 10 An Organizational Tree for a Computer Company.

system. Thus, a file system may be represented by a rooted tree, where the root represents the
root directory, internal vertices represent subdirectories, and leaves represent ordinary files or
empty directories. One such file system is shown in Figure 11. In this system, the file khr is in
the directory rje. (Note that links to files where the same file may have more than one pathname
can lead to circuits in computer file systems.)


The root is the root directory /
Tính chất của Cây / Internal vertices are directories
Leaves are files

u Định lý 1. Giả sử T = (V, E) là đồ thị vô hướng n đỉnh. Khi đó, các


mệnh đề sau đây là tương
usr đương: bin tmp

u 1) T là cây
u 2) T không chứa
bin
churje trình và có n mail
spool ls
- 1 cạnh
who junk
u 3) T liên thông và có n – 1 cạnh
u 4) T liên thông và mỗi cạnh của nó đều là cầu
u 5) Hai đỉnhedbất
nroffkỳvicủa
khr T
oprđược
uucp nối với nhau bằng đúng 1 đường đi đơn

u 6) T không chứa chu trình nhưng hễ cứ thêm vào nó 1 cạnh ta thu được
đúng 1 chu trình
printer file

u Chứng minh:FIGURE 11 =>


1) => 2) A Computer
3) => 4)File
=>System.
5) => 6) => 1)?

EXAMPLE 8 Tree-Connected Parallel Processors In Example 17 of Section 10.2 we described several


interconnection networks for parallel processing. A tree-connected network is another impor-
P1
tant way to interconnect processors. The graph representing such a network is a complete binary
tree, that is, a full binary tree where every root is at the same level. Such a network interconnects
P2 P3 n = 2k − 1 processors, where k is a positive integer. A processor represented by the vertex v
that is not a root or a leaf has three two-way connections—one to the processor represented by
connecting any two towns. How can this be done?
At least five roads must be plowed to ensure that there is a path between any two towns.
Figure 1(b) shows one such set of roads. Note that the subgraph representing these roads is a
tree, because it is connected and contains six vertices and five edges.
11.4 Spanning Trees 785
11.4 Cây khung This problem
của đồ was solved
thị with a connected subgraph with the minimum number of edges
Etna Old Town
containing
Etna
all vertices
Old Town
of the original simple graph. Such a graph must be a tree.
u Định nghĩa: Giả sử G = (V, E) là đồ thị vô a b c d

Herman
hướng liênHerman
Orono thông. Cây T =Orono
Bangor
(V, F), với F ⊂ E
Bangor
được gọi là CÂY KHUNG của đồ thị G.
Hampden DEFINITION 1 Hampden
Let G be a simple graph. A spanning tree of G ise a subgraph of G that isg a tree containing
f
(a) every vertex(b)of G.
u Tìm cây khung của đồ thị G trong hình 2.
FIGURE 1 (a) A Road System and (b) a Set FIGURE 2 The
of Roads to Plow. Simple Graph G.
A simple graph with a spanning tree must be connected, because there is a path in the
Let G be a simple graph. A spanning tree of G is
u
a subgraph of spanning
G that treeisbetween
a treeany two vertices. every
containing The converse is also true; that is, every connected
ning Treesvertex of G. simple graph has a spanning tree. We will give an example before proving this result.
EXAMPLE 1 Find a spanning tree of the simple graph G shown in Figure 2.
Introduction
Consider the system of roads Solution:
in Maine Therepresented by the simple
graph G is connected, graph
but it is not a treeshown
becauseinit Figure
contains 1(a).
simple circuits.
The only way the roads can be kept open in the winter is by frequently plowing them. The
ighway department wants to Remove
plow the the edge
fewest{a,e}.roads
This so
eliminates one simple
that there will circuit,
alwaysandbethecleared
resultingroads
subgraph is still
onnecting any two towns. How connected
can thisand be contains every vertex of G. Next remove the edge {e,f} to eliminate a
stilldone?
At least five roads must be plowed
second simpletocircuit.
ensure thatremove
Finally, is a {c,g}
there edge path tobetween
produce aanysimpletwograph
towns.
with no simple
Figure 1(b) shows one such set of roads. Note that the subgraph representing these roads is a
circuits.
ree, because it is connected and This subgraph
contains is a spanning
six vertices tree, edges.
and five because it is a tree that contains every vertex of G.
This problem was solved The withsequence of edge removals
a connected subgraph used with
to produce
the the spanning tree
minimum is illustrated
number in Figure 3.
of edges
Ví dụ
ontaining all vertices of the original simple graph. Such a graph must be a tree.

a b c d a b c d a b c d
Let G be a simple graph. A spanning tree of G is a subgraph of G that is a tree containing
every vertex of G.

A simple graph e g
with a spanning e tree must be gconnected, e because there g is a path in the
f f f
panning tree between any two vertices. The converse is also true; that is, every connected
imple graph has a spanning tree. We will give an example before proving this result.
Edge removed: {a, e} {e, f} {c, g}
Find a spanning tree of the simple graph G shown in Figure 2.
(a) (b) (c)
olution: The graph G is connected, but it is not a tree because it contains simple circuits.
edge {a,3 e}.
Remove the FIGURE This eliminates
Producing a Spanningone
Tree simple
for G by circuit,
Removingand theThat
Edges resulting subgraph
Form Simple Circuits.is still
onnected and still contains every vertex of G. Next remove the edge {e, f } to eliminate a
econd simple circuit. Finally, remove edge {c, g} to produce a simple graph with no simple
ircuits. This subgraph is a spanning tree, because it is a tree that contains every vertex of G.
The sequence of edge removals used to produce the spanning tree is illustrated in Figure 3.
MHIA017-Rosen-v5.cls May 13, 2011 10:27

Theorem 1. A simple graph is connected if and only


if it has a spanning tree.
es

u A
a b c d a b c d

e g
e f g f

a b c d a b c d

e g
e f g f

FIGURE 4 Spanning Trees of G.

The tree shown in Figure 3 is not the only spanning tree of G. For instance,
shown in Figure 4 is a spanning tree of G.

REM 1 A simple
A017-Rosen-v5.cls graph 10:27
May 13, 2011 is connected if and only if it has a spanning tree.

Proof: First, suppose that a simple graph G has a spanning tree T . T contains ev
Furthermore, there is a path in T between any two of its vertices. Because T is a
11.2 Ứng dụng: IP Multicasting
there is a path in G between any two of its vertices. Hence, G isSpanning
11.4 Trees 78
connected.
Now suppose that G is connected. If G is not a tree, it must contain a simple
an edge from one of these simpleMulticast
IP network circuits. The
spanning treeresulting subgraph has one few
contains all the vertices of G and is connected. This subgraph is still connecte
Source Source
two vertices are connected by a path containing the removed edge, they are con
not containing this edge. We can construct such a path by inserting into the o
the point where the removed edge once was, the simple circuit with this edge
subgraph is not a tree, it has a simple circuit; so as before, remove an edge th
circuit. Repeat this process until no simple circuits remain. This is possible be
only a finite number of edges in the graph. The process terminates when no
remain. A tree is produced because the graph stays connected as edges are rem
is a spanning tree because it contains every vertex of G.

Spanning trees are important in data networking, as Example 2 shows.


(a) (b)
MPLE 2 IP Multicasting Spanning trees play an important role in multicasting over I
(IP) networks. ToRouter send data from a source computer to multiple receiving com
which is a subnetwork, data could be sent separately to each computer. This type
Subnetwork
called unicasting,Subnetwork
is inefficient, because
with a receiving station many copies of the same data are tran
network. To make the transmission of data to multiple receiving computers m
FIGURE 5 A Multicast Spanning Tree.
multicasting is used. With IP multicasting, a computer sends a single copy o
network, and as data reaches intermediate routers, the data are forwarded to on
routers
router. Toso thatloops,
avoid ultimately all receiving
the multicast routers use computers in their various
network algorithms subnetworks
to construct re
a spanning tre
(Routers are computers that are dedicated to forwarding IP datagrams
in the graph that has the multicast source, the routers, and the subnetworks containing receivingbetween
a network.
computers as In multicasting,
vertices, with edgesrouters use the
representing Class Dbetween
links addresses, each and/or
computers representing
routers
receiving
The root of computers
this spanningmay tree join;
is the see Example
multicast 17The
source. in Section 6.1.)
subnetworks containing receiving
computers are leaves
For data of thereceiving
to reach tree. (Note computers
that subnetworks not containing
as quickly receivingthere
as possible, stations ar
shou
Rosen-v5.cls May 13, 2011 10:27

Định lý Cayley.
u Số cây khung của đồ thị Kn là nn-2 11.4 Spanning T
u Chứng minh?

explore from a vertex v when we carry out the steps of depth-first search beginning w
u Áp
added todụng thuậtand
the tree toán tìm kiếm,
ending whenxây
wedựng
havecây khung T của
backtracked back to v for the last time.
đồ thị vô
observation hướngtoliên
needed thông G cho
understand the bởi danh sách
recursive kề:of the algorithm is that when w
nature
edge connecting a vertex
u Tìm kiếm theo to a(BFS)
chiềuvrộng vertex w, we finish exploring from w before we retur
complete exploring
u Tìm kiếm theofrom
chiềuv.sâu (DFS)
In Algorithm 1 we construct the spanning tree of a graph G with vertices v1 , . . . , v
selecting the vertex v1 to be the root. We initially set T to be the tree with just this on
At each step we add a new vertex to the tree T together with an edge from a vertex
in T to this new vertex and we explore from this new vertex. Note that at the comp
the algorithm, T contains no simple circuits because no edge is ever added that conn
vertices in the tree. Moreover, T remains connected as it is built. (These last two obs
can be easily proved via mathematical induction.) Because G is connected, every ve
is visited by the algorithm and is added to the tree (as the reader should verify). I
that T is a spanning tree of G.

Tìm kiếm theo chiều sâu (DFS)


ALGORITHM
u 1 Depth-First Search.

procedure DFS(G: connected graph with vertices v1 , v2 , . . . , vn )


T := tree consisting only of the vertex v1
visit(v1 )

procedure visit(v: vertex of G)


for each vertex w adjacent to v and not yet in T
add vertex w and edge {v, w} to T
visit(w)

We now analyze the computational complexity of the depth-first search algorithm


observation is that for each vertex v, the procedure visit(v) is called when the vertex
P1: 1
CH11-7T Rosen-2311T MHIA017-Rosen-v5.cls May 13, 2011 10:27

Ví dụ
788 11 / Trees
u Use depth-first search to find a spanning tree for the
graph G shown in Figure 6.
f f f
a d i j
g g
h h
f k k
c
e h k i
j j

b g (a) (b) (c)

FIGURE 6 The Graph G. FIGURE 7 Depth-First Se

The reader should note the recursive nature of this pro


in the graph are ordered, the choices of edges at each stage
when we always choose the first vertex in the ordering tha
always explicitly order the vertices of a graph.
Depth-first search is also called backtracking, becau
13, 2011 10:27 previously visited to add paths. Example 3 illustrates back

Kết quả EXAMPLE 3 Use depth-first search to find a spanning tree for the graph

u The steps used by depth-first search to The


Solution: stepsaused by depth-first search to produce
produce
spanning tree of G are shown Figure 7. We
in Figure 7 arbitrarily start with the vertex f . A path is
incident with vertices not already in the path, as long as t
f f
f , fg, h, k, j (note that
f
other paths could have been built
f
path beginning at k containing vertices not already visite
j
g g gpath h, d i. Then backtrack
g dto h, and then to f . From f build
h h h to c ande form theh path c, b.e This produces the spanning tre
k k k c k c
k i i i
The edges selected by depth-first search of a graph ar
j j j a j
of the graph must connectb a vertex
a
to an ancestor or descen
(a) (b) (c) (d) are called back
edges (e)edges. (Exercise 43 asks for a proof

FIGURE 7 Depth-First Search of G.


EXAMPLE 4 In Figure 8 we highlight the tree edges found by depth-first s
them with heavy colored lines. The back edges (e, f ) and
should note the recursive nature of this procedure.lines.
Also, note that if the vertices
ordered, the choices of edges at each stage of the procedure are all determined
s choose the first vertex in the ordering that is available. However,
We have we will
explained hownotto find a spanning tree of a grap
y order the vertices of a graph. our discussion so far has not brought out the recursive n
-Rosen-v5.cls May 13, 2011 10:27

11.4 Spanning Trees 79

Tìm kiếm theo chiều rộng (BFS)


ALGORITHM 2 Breadth-First Search.

procedure BFS (G: connected graph with vertices v1 , v2 , . . . , vn )


T := tree consisting only of vertex v1
L := empty list
put v1 in the list L of unprocessed vertices
while L is not empty
remove the first vertex, v, from L
for each neighbor w of v
if w is not in L and not in T then
add w to the end of the list L
add w and edge {v, w} to T

We now analyze the computational complexity of breadth-first search. For each vertex v i
the graph we examine all vertices adjacent to v and we add each vertex not yet visited to th
tree T . Assuming we have the adjacency lists for the graph available, no computation is require
to determine which vertices are adjacent to a given vertex. As in the analysis of the depth-fir
sen-2311Tsearch algorithm, we see that we
MHIA017-Rosen-v5.cls examine
May 13, 2011each edge
10:27at most twice to determine whether w
should add this edge and its endpoint not already in the tree. It follows that the breadth-fir
search algorithm uses O(e) or O(n2 ) steps.
Breadth-first search is one of the most useful algorithms in graph theory. In particular, it ca
Ví dụ
serve as the basis for algorithms that solve a wide variety of problems. For example, algorithm
0
thatufind
11 / Trees Usethe connected components
breadth-first of a graph,
search to find that determine
a spanning whether a graph is bipartite, an
tree for the
that find the shown
graph path with the fewest
in Figure 9. edges between two vertices in a graph can all be built usin
breadth-first search.
a b c l

Backtracking Applications
e f
d g
There are problems that can be solved only by performing an exhaustive search of all possib
solutions. One way to searchi systematically for a solution is to use a decision tree, where eac
h
internal vertex represents a decision and each leaf a possible solution. To find a solution v
j
backtracking, first make a sequence of decisions in an attempt to reach a solution as long as th
is possible. The sequence of decisions can be represented by a path in the decision tree. Onc
it is known that no m
solution can
k result from any further sequence of decisions, backtrack to th
parent of the current vertex and work toward a solution with another series of decisions, if this
FIGURE
possible. The procedure 9 A
continues Graph
until a solution
G. is found, or it is established that no solutio
exists. Examples 6 to 8 illustrate the usefulness of backtracking.
LE 6 Graph Colorings How can backtracking be used to decide whether a graph can be colore
using n colors? edges incident to this vertex. The new vertices added at this sta
in the spanning tree. Arbitrarily order them. Next, for each v
the vertex e to be the root. Then we add edges incident with all vertices adjacent to e, so edges
from e to b, d, f , and i are added. These four vertices are at level 1 in the tree. Next, add the
edges from these vertices at level 1 to adjacent vertices not already in the tree. Hence, the edges
from b to a and c are added, as are edges from d to h, from f to j and g, and from i to k. The
new vertices a, c, h, j , g, and k are at level 2. Next, add edges from these vertices to adjacent
vertices not already in the graph. This adds edges from g to l and from k to m.


Kết quả
We describe breadth-first search in pseudocode as Algorithm 2. In this algorithm, we assume
the vertices of the connected graph G are ordered as v , v , . . . , v . In the algorithm we use the
1 2 n
term “process” to describe the procedure of adding new vertices, and corresponding edges, to
the tree adjacent to the current vertex being processed as long as a simple circuit is not produced.

e e e e

b d f i b d f i
b d f i

a c h g j k a c h g j k

l m

FIGURE 10 Breadth-First Search of G.

A017-Rosen-v5.cls May 13, 2011 10:27

11.2 Applications of Trees 759

Binary Search Tree


ALGORITHM 1 Locating an Item in or Adding an Item to a Binary Search Tree.

procedure insertion(T : binary search tree, x: item)


v := root of T
{a vertex not present in T has the value null }
while v != null and label(v) != x
if x < label(v) then
if left child of v != null then v := left child of v
else add new vertex as a left child of v and set v := null
else
if right child of v != null then v := right child of v
else add new vertex as a right child of v and set v := null
if root of T = null then add a vertex v to the tree and label it with x
else if v is null or label(v) != x then label new vertex with x and let v be this new vertex
return v {v = location of x}

Example 2 illustrates the use of Algorithm 1 to insert a new item into a binary search tree.
these tasks, even though it may appear that it is only designed to add vertices to a binary search
tree. That is, Algorithm 1 is a procedure that locates an item x in a binary search tree if it is
present, and adds a new vertex with x as its key if x is not present. In the pseudocode, v is the
vertex currently under examination and label(v) represents the key of this vertex. The algorithm
begins by examining the root. If x equals the key of v, then the algorithm has found the location
of x and terminates; if x is less than the key of v, we move to the left child of v and repeat the
procedure; and if x is greater than the key of v, we move to the right child of v and repeat the
procedure. If at any step we attempt to move to a child that is not present, we know that x is not
present in the tree, and we add a new vertex as this child with x as its key.
Ví dụ
mathematics mathematics mathematics mathematics

physics
physics geography physics geography

zoology

zoology > mathematics


IA017-Rosen-v5.cls May 13, 2011 10:27physics > mathematics geography < mathematics zoology > physics
mathematics mathematics mathematics mathematics
geography geography geography
physics physics physics
geography geology physics
geology zoology geology zoology zoology
meteorology zoology meteorology meteorology chemistry
11.2 Applications of Trees 761
psychology meteorology psychology
psychology > mathematics
meteorology > mathematics geology
1 <2 mathematics
3 psychology
4 5 6> physics chemistry < mathematics
meteorology < physics geology > geography psychology < zoology chemistry < geography

FIGURE 1 Constructing a Binary Search Tree.


Lighter 1 2 3 Balance 4 5 6 Lighter

1 2 7 8 4 5

1 Lighter Balance 2 Lighter 7 Lighter Balance 8 Lighter 4 Lighter Balance 5 Lighter


1 3 2 7 Impossible 8 4 6 5

FIGURE 3 A Decision Tree for Locating a Counterfeit Coin. The counterfeit coin is shown in color
Decision Trees
elow each final weighing.

AMPLE 4 uA
We sorting
display algorithm
in Figure based tree
4 a decision on binary comparisons
that orders the elements of the list a, b, c.
requires at least ⌈log n!⌉ comparisons ▲

a:b

a>b a<b

a:c b:c

a>c a<c b>c b<c

b:c c>a>b a:c c>b>a

b>c b<c a>c a<c

a>b>c a>c>b b>a>c b>c>a

FIGURE 4 A Decision Tree for Sorting Three Distinct Elements.

The complexity of a sort based on binary comparisons is measured in terms of the number
of such comparisons used. The largest number of binary comparisons ever needed to sort a list
with n elements gives the worst-case performance of the algorithm. The most comparisons used
equals the longest path length in the decision tree representing the sorting procedure. In other
11.3 Xây dựng tập các chu trình cơ bản của
đồ thị (Duyệt cây)
u Bài toán xây dựng cây khung của đồ thị
u Giả sử G = (V, E) là đơn đồ thị vô hướng liên thông,
H = (V, T) là cây khung của nó
u Cạnh trong: các cạnh thuộc cây khung
u Cạnh ngoài: các cạnh còn lại

u Nếu thêm 1 cạnh ngoài e ∈ E \ T vào cây khung H, chúng ta


sẽ thu được đúng 1 chu trình trong H, ký hiệu chu trình này là
Ce. Tập các chu trình Ω = {Ce : e ∈ E \ T} được gọi là tập các
chu trình cơ bản của đồ thị G.

Bài toán cây khung nhỏ nhất


u Bài toán tối ưu trên đồ thị
u G = (V, E): đồ thị vô hướng liên thông
u Tập đỉnh V = {1, 2, …, n}
u Tập cạnh E (m cạnh)
u c(e): độ dài cạnh e
uH = (V, T): cây khung của đồ thị G
u Độ dài c(H): tổng độ dài của các cạnh của cây khung H

u Tìm cây khung có độ dài nhỏ nhất?


Nối mạng máy tính
u Cần nối mạng 1 hệ thống gồm n máy vi tính đánh số từ
1 đến n. Biết chi phí nối máy i với máy j là c[i, j]; i, j =
1, 2, …, n

u Tìm cách nối mạng sao cho tổng chi phí nối mạng là
nhỏ nhất?

u Phương án:
u Thuật toán Kruskal+ ^ ủ Bi + + ủủủ ¡ u + ^

Thuật toán Prim


u
v h ộ â I ù ể ểè Đ ũ k ãù ỏ1 ề

â Iù ể ểèĐũ ỏ ởẳắ ồ ũP ể ỹ ổ ũI ủr ổ ề ổHắ 1IùũP ũI ũI ể đ hạ 7k á ểIịè ể ũP : ổ


âã ổ I ể ở ỹ ở ỹ ổĐổ ổ ũI ổ ề ểI o ểIịè ểI ể 1I ũP P4 e ổ ề ồH4 . ể ù ể
ể ỹ k I17 e 4 : ổ ểề ỏ ò ũ ò ể ồùắ ể ểãèũP ồềũI ỏĐổI ổ ũI 2 ở ỹ ở ỹc ể ổ ũI ổ9
ồH4 ũI ũ ổ ũI ổ9 ồH4 ò ũ I ũc ể8e ãề ổ ũI e H ẫ4 ổ : ỏùũP ũ9 ẫHè ể ỹ k
1I ũP ể è ểIHũI ổIù ểã8ũI ểãèũP ể ỹ ũHắ âIù ể ểèĐũ ỏ 1 ể ểI ổ 1I4 ểề ểIù ổ ể ỹ k
e àủlộ C ũò4 C ểI c ểIù ể ểổĐã ổv gI ũ ù ũI4r ậ ùg
Thuật toán Kruskal
ỹ ãè ổ ị ồ ù ãị k ãù ỏ1 ề òê
:ịP4ũ
â gu m ê
ặ I4òị ụ â ụ ứ ờũlội ềũồ ờ s m i ồè
:ịP4ũ
p N \ b }R X \N X Y{Y \N \N s sýj\= )a
sgusýQịiê
4N ờ â ù ờố ỂN \= XN A XN' sý<\N i ểIịũ â gu â ù ị ụ ê
ịũồê
4N ờ ụ â ộứ ũlộ i ểIịũ N ỂN \= }{„\ s}< \=a
ịũồê

âIG ồ hc â4e ổẳắ 1IùũP ũI ũI ể ổ ề ểI ổIè ểãèũP I8ũI h

ợ X ỂN { ý jă ể k gu m ở ỹ ổĐổ ổ ũI ổ ề ểI ểIịè ểI ể 1I ũP P4 e ổ ề
Tìm cây khung nhỏ nhất của đồ thị trong Hình 4.
lN ịă â N N
u T = {(3,5), (4,6), (4,5), (1,3), (2,3)}. Lập trình thực hiện thuật toán?

ếu
HIA017-Rosen-v5.cls May 13, 2011 10:27

11.5 Minimum Spanning Trees 799

$2000 New York


Chicago
$1000
co $1200 00
$90
0 $13 3 E ổt E ậ Đa 2 b 3 c 1 d
$1600
0
$80

Denver
$7
00

$1400
ì ợt d I v 4 I I I ổ 1I P 3I I 1ổ ề 2 I ổI 5 P I I
$2200
ổ ổ I ò ổ ổ ổ I ổ Atlanta
ổI ổ 1I Pc ổ ổ ổề I ò ò ổ ổ ổ I
4 f 3 g 3
: Choice
ề P Edge I ồ Cost
ề ổ ổ ổ I e h
1 {Chicago, Atlanta} $ 700
2 {Atlanta, New York} $ 800 4 2 4 3
3 {Chicago, San Francisco} $ 1200
4 {San Francisco, Denver} $ 900 3 3 1
Thuật toán Prim Total: $ 3600 i j k l

u Thuật toán Kruskal không hiệu quả với những đồ thị


E 2 A Minimum Spanning Tree for the Weighted FIGURE 3 A Weighted Graph.
n Figure 1. dày (số cạnh m ~ n(n-1)/2)
u Phương pháp lân cận gần nhất: Thuật toán Prim

ALGORITHM 1 Prim’s Algorithm.

procedure Prim(G: weighted connected undirected graph with n vertices)


T := a minimum-weight edge
for i := 1 to n − 2
e := an edge of minimum weight incident to a vertex in T and not forming a
simple circuit in T if added to T
3 T :=E Tợtwith
â4e added
ổ 1I P I I Iị I k ổềò
return T {T is a minimum spanning tree of G}
Đ ờH E E Đ ậ ễ E t

P I I ổ Iị I ổ àủlộ ổ I 1I P ổ ổI Ic Iị
ò ộ ò Note
ổ that 1I
the choice
P ổof ềan edge Ito add
oă atếaIstage of the algorithm
c ổI ổ is Inot4 determined
ổI ề when P there
k ổ ồ 4
I ử4
is more than 4oneổ edge with
ổ ề
the sameI weight
o
thatXsatisfies the appropriate criteria.
ệá V Xhkáă k I4
We need to
b7 ò ổ I 4
order the edges to make the choices deterministic. We will not worry about this in the remainder
:ịP4ũ
ồxẫb gu ổxùcẫb ê
ồxẫb gu guổxùcẫb
ũịềãxẫb ùê ê
ịũồê ũịềãxẫb gu ùê
ứ ìà ịũồê
ịũồê
Tìmứ cây
ìà khung nhỏ nhất cho đồ thị Hình 4
ịũồê thuật toán Prim?
theo
âI4 ồ ự â4e ổẳắ 1IùũP ũI ũI ể ổIè ểI ở ể ểãèũP ểI ồ h ểIịè ểIù ể ểèĐũ qã4e
ả ề ểã ũ ểã ũP ỏ ổ ề ểI ổ ồ ũP
â I4Ma
u
ồ trận trọng
ự â4e số: ũI ũI ể ổIè
ổẳắ 1IùũP ểI ở ể ểãèũP ểI ồ h ểIịè ểIù ể ểèĐũ qã4e
ảề ểã ũ ểã ũP ỏ ổ ề ộ ểI ổ t ồ ũP ĩ h v ự
ộ m ĩĩ ộủ mm mm ổè
t ĩĩộ tm ĩộa h tm v mm ự mm
C u ĩ ộ ộủm ĩĩ
ộa ộủ m mm ộự mm h ổè mm
h t ĩĩ
mm tmm ộaộự tm m mm ọ mm a
C u v ĩ mm
ộủ ổè
ộa m h ộự ọ h m mm ộh
ự hơ mmmm mm
tm ộựổè m a ọ ộh a m ơ
. ũP ồ 4 ẳắ mm ổèổ ề ổĐổ
v PI4 ũI2ũ h ọũI ểãèũP
m ộhổĐổ : ổ ò ỹ ổ ề ểIù ể ểèĐũc ũI Đũ
ồ ù ạ òH ũI ựổ ổI
ơ ũmm mm
: ỏùũPổè ẫHè ổẳắ 1IùũP ờ1I4 ũI2ũ ổ ề ũ 1I ũP ổ ũ :
a ộh m ơ
:4 ũ 4 ểãèũP ổĐổ : ổ ò ỹ ể4 ỹ ểIịèc ẫ ẫ ắ ễ ĐũI ồ ù l PI4 ũI ũ 4 ù i g
. ũP ồ 4 ẳắ PI4 ũI2ũ ổ ề ổĐổ ũI ểãèũP ổĐổ : ổ ò ỹ ổ ề ểIù ể ểèĐũc ũI ĐũI
6 ồậ ù ạ òH ũI ổ ổI ũ : ỏùũP ẫHè ổẳắ 1IùũP ờ1I4 ũI2ũ ổ ề ũ 1I ũP ổ ũ :
9 :4 ũ 4 ểãèũP
E y ổĐổ E: ế ổ ò ỹ ể4
E ỹT ểIịècũIẫ hẫ ắ ễ E ĐũI
ợ ồH ùE l p PI4 ũI ũ 4 ù ig b
Nhãn các đỉnh trong các bước lặp
rE H ịu y7 ịTT y7 ịyM y7. ịg 7 ygg y7 y y7 y u
6 ậ
y
9
l
E y
xộacĩb
E ế
l
E T
ị yp TD
ũI h
ịổ T7.
E ợ
r
H E p
y T
b
nT yỉ
ế l ịyở T7 l yđt ợ7. ) ị y ổ ợD y T ợ nT yỉ nợ Tỉ
T l ịyở T7 l l l xachbạ y T ợ ổ nT yỉ n ợ T ỉ nổtợỉ
h rE H lịu y7ị y ở ịt TTTy .y 7 ịyM l y7. ịg 7
l ygg y7 l y y7 y
y T ợ ổ p u
ờĩcộic ờvcĩic ờhcvic ờựchi
r
v y l xộacĩb ol ịyp TD ịổ T7. r y yT T ợ ổ p ế nT yỉn T y ỉ n ợ T ỉ n ổ ợ ỉ

ế l ịyở T7 l yđtợ7. ) ịyổ ợD y T ợ nT yỉ nợ Tỉ ờựchic ờt ĩi


T l ịyở T7 l l l xachbạ y T ợ ổ nT yỉ n ợ T ỉ nổtợỉ
h l ịy ở tT y . l l l y T ợ ổ p ờĩcộic ờvcĩic ờhcvic ờựchi
r
v o y T ợ ổ p ế nT yỉ nợ Tỉ nổ ợỉ
tộ
ờựchic ờt ĩi

tộĩ
Một số bài toán cây khung nhỏ nhất
u Bài toán cây khung lớn nhất
u Đòi hỏi về dấu của trọng số?
u Phải tìm cây lớn nhất?
u Giải pháp: đổi dấu tất cả các độ đo

u Bài toán tìm mạng điện với độ tin cậy lớn nhất
u Cho lưới điện có n nút
u Đường dây nối nút i với nút j có độ tin cậy 0 < p[i,j] < 1
u Tìm cây khung H của đồ thị G = (V, E) với độ tin cậy lớn nhất

! p(e)
"∈#

Ta có: pN =v C p ít MpX Y

ò P ờị i ứ lbớ ò Pàố ổoi


bbm boăỲ t

4 e 4 ổ 1I ũP à à r ổ ề I oă â ề

ớ ò P ờị i đ ớ = bá
bđ Mđt

mNđũ l rr ẽ4 bbđt

Iề ò

ũb đ
l ũ bMđt

4 e 4 ổ 1I ũP đ í ì đ ò ổ 1I ũP ổ 4ũ ổ ò ũ ũI
15. Find a maximum spanning tree for the weighted graph in ∗ 24. Show that the addition of edges at each stage of Sollin’s
Exercise 4. algorithm produces a forest.
16. Find the second least expensive communications network 25. Use Sollin’s algorithm to produce a minimum spanning
connecting the five computer centers in the problem posed tree for the weighted graph shown in
at the beginning of the section.
∗ 17. Devise an algorithm for finding the second shortest span- a) Figure 1.
ning tree in a connected weighted graph. b) Figure 3.
∗ 18. Show that an edge with smallest weight in a connected ∗ 26. Express Sollin’s algorithm in pseudocode.
weighted graph must be part of any minimum spanning ∗∗ 27. Prove that Sollin’s algorithm produces a minimum span-
tree. ning tree in a connected undirected weighted graph.
Tổng kết
19. Show that there is a unique minimum spanning tree in a
connected weighted graph if the weights of the edges are
∗ 28. Show that the first step of Sollin’s algorithm produces a
forest containing at least "n/2# edges when the input is
all different.
an undirected graph with n vertices.
20. Suppose that the computer network connecting the cities
in Figure 1 must contain a direct link between New York ∗ 29. Show that if there are r trees in the forest at some interme-
Cây và Cây khung
u and Denver. What other links should be included so that diate step of Sollin’s algorithm, then at least "r/2# edges
are added by the next iteration of the algorithm.
there is a link between every two computer centers and
the cost is minimized? ∗ 30. Show that when given as input an undirected graph with n
21. Find a spanning tree with minimal total weight contain- vertices, no more than $n/2k % trees remain after the first
ing the edges {e, i} and {g, k} in the weighted graph in step of Sollin’s algorithm has been carried out and the
Thuật toán
u Figure 3. second step of the algorithm has been carried out k − 1
22. Describe an algorithm for finding a spanning tree with times.
minimal weight containing a specified set of edges in a ∗ 31. Show that Sollin’s algorithm requires at most log n iter-
connected weighted undirected simple graph.
ations to produce a minimum spanning tree from a con-
23. Express the algorithm devised in Exercise 22 in pseu-
Ứng dụng
u docode. nected undirected weighted graph with n vertices.
Sollin’s algorithm produces a minimum spanning tree from 32. Prove that Kruskal’s algorithm produces minimum span-
a connected weighted simple graph G = (V , E) by succes- ning trees.
sively adding groups of edges. Suppose that the vertices in V 33. Show that if G is a weighted graph with distinct edge
Q&A
are ordered. This produces an ordering of the edges where
u0 , v0 } precedes {u1 , v1 } if u0 precedes u1 or if u0 = u1
{u
weights, then for every simple circuit of G, the edge of
maximum weight in this circuit does not belong to any
and v0 precedes v1 . The algorithm begins by simultaneously minimum spanning tree of G.
choosing the edge of least weight incident to each vertex. The When Kruskal invented the algorithm that finds minimum
first edge in the ordering is taken in the case of ties. This pro- spanning trees by adding edges in order of increasing weight
duces a graph with no simple circuits, that is, a forest of trees as long as they do not form a simple circuit, he also invented
(Exercise 24 asks for a proof of this fact). Next, simultaneously another algorithm sometimes called the reverse-delete al-
choose for each tree in the forest the shortest edge between a gorithm. This algorithm proceeds by successively deleting
vertex in this tree and a vertex in a different tree. Again the first edges of maximum weight from a connected graph as long as
edge in the ordering is chosen in the case of ties. (This pro- doing so does not disconnect the graph.
duces a graph with no simple circuits containing fewer trees
than were present before this step; see Exercise 24.) Continue 34. Express the reverse-delete algorithm in pseudocode.
the process of simultaneously adding edges connecting trees 35. Prove that the reverse-delete algorithm always produces
until n − 1 edges have been chosen. At this stage a minimum a minimum spanning tree when given as input a weighted
spanning tree has been constructed. graph with distinct edge weights. [Hint: Use Exercise 33.]

Key Terms and Results

P1: 1
TERMS parent of v in a rooted tree: the vertex u such that (u, v) is an
CH11-7T Rosen-2311T MHIA017-Rosen-v5.cls May 13, 2011 10:27 edge of the rooted tree
tree: a connected undirected graph with no simple circuits
child of a vertex v in a rooted tree: any vertex with v as its
forest: an undirected graph with no simple circuits parent
rooted tree: a directed graph with a specified vertex, called the sibling of a vertex v in a rooted tree: a vertex with the same
root, such that there is a unique path to every other vertex parent as v
804from11this root
/ Trees ancestor of a vertex v in a rooted tree: any vertex on the path
subtree: a subgraph of a tree that is also a tree from the root to v

descendant of a vertex v in a rooted tree: any vertex that has postorder traversal: a listing of the vertices of an ordered
v as an ancestor rooted tree defined recursively—the subtrees are listed in
internal vertex: a vertex that has children the order they occur from left to right, followed by the root
leaf: a vertex with no children infix notation: the form of an expression (including a full set
level of a vertex: the length of the path from the root to this of parentheses) obtained from an inorder traversal of the
vertex binary tree representing this expression
height of a tree: the largest level of the vertices of a tree prefix (or Polish) notation: the form of an expression ob-
m-ary tree: a tree with the property that every internal vertex tained from a preorder traversal of the tree representing this
has no more than m children expression
full m-ary tree: a tree with the property that every internal postfix (or reverse Polish) notation: the form of an expression
vertex has exactly m children obtained from a postorder traversal of the tree representing
binary tree: an m-ary tree with m = 2 (each child may be this expression
designated as a left or a right child of its parent) spanning tree: a tree containing all vertices of a graph
ordered tree: a tree in which the children of each internal minimum spanning tree: a spanning tree with smallest pos-
vertex are linearly ordered sible sum of weights of its edges
balanced tree: a tree in which every leaf is at level h or h − 1,
where h is the height of the tree
RESULTS
binary search tree: a binary tree in which the vertices are la-
beled with items so that a label of a vertex is greater than A graph is a tree if and only if there is a unique simple path
the labels of all vertices in the left subtree of this vertex and between every pair of its vertices.
is less than the labels of all vertices in the right subtree of A tree with n vertices has n − 1 edges.
this vertex A full m-ary tree with i internal vertices has mi + 1 vertices.
decision tree: a rooted tree where each vertex represents a The relationships among the numbers of vertices, leaves, and

You might also like