Вы находитесь на странице: 1из 4

Consider the function Mystery defined below.

Mystery(n)
if n 1 then begin
for i := 1 to n1/2 print(x);
Mystery(n/4);
Mystery(n/4);
end
(a) How many xs does Mystery(1) print? How many xs
does Mystery(4) print?
(b) If we call Mystery(n), where n is a power of 4 and n
1, how many xs (as a function of n) does call Mystery(n)
print? Justify your answer/show your work (ie give
recurrence and solve by substitution.)
Hint: Using 4k = 22k and taking logs base 2 makes
calculations easier.
Answer:
(a) Mystery(1) prints one x. Mystery(4) prints four xs.
(b) We have to solve T(n) = 2T( n 4 ) + n 1 2 for all n 1,
with T(1) = 1. Solve by substitution.

So Mystery prints n (1 +

!"#! !
!

with T (1) = 1 since 11/2 (1 +


4

1/2

(1 +

!"#! !
!

) xs (which is consistent

!"#! !
!

) = 1 and T (4) = 4 since

)=4

Problem 2: Graph Representation


Let G (V, E) be an undirected graph given in adjacency list
representation (without redundancies, i.e. each vertex
appears at most once in an adjacency list.) The degree of a
vertex v V is the number of vertices u that are adjacent
to v: deg(v) = |{u : u Adj(v)}|. The twodegree of a vertex
v V is the sum of the degrees of the vertices that are
adjacent to v: twodeg(v) = uAdj(v) deg(u).
(a) Give an O(|V | + |E|) time algorithm that computes
deg(v), for all v V .
(b) Give an O(|V | + |E|) time algorithm that computes
twodeg(v), for all v V .
Answer:
(a) To compute degrees scan the adjacency lists of all
vertices. Since there are no redundancies, every vertex in an
adjacency list of a vertex v adds one to the degree of v.
for all v V set deg(v) := 0;
for all v V
for all u Adj(v) set deg(v) := deg(v) + 1;
The total time is O(|V |+|E|), each vertex is considered once
in the first and second lines, and each edge {u, v} is
considered twice in the second line, once in the adjacency
list of u and once in the adjacency list of v.
(b) To compute twodegrees, after the degrees have been
computed in part (a), again scan the adjacency lists of all
vertices. For every vertex u in an adjacency list of a vertex
v add deg(u) to the twodegree of v.
for all v V set twodeg(v) := 0;
for all v V
for all u Adj(v) set twodeg(v) := twodeg(v) +
deg(u);
The total running time is O(|V | + |E|), arguing exactly as in
part (a).
Problem 3: DFS
Give an O(|V | + |E|) algorithm which takes as input a
directed graph G = (V, E), and determines whether or not
there exists a vertex v V from which all other vertices
are reachable. Justify correctness and running time.
Hint: First solve the problem for the case where G is
acyclic.
Answer:
If G(V, E) is acyclic, then it has a topological sorting.
The only vertex of V that can possibly reach all other

vertices is the vertex that is first in topologically sorted


order; say r (since all other vertices are ahead of r in
topological order and thus cannot have an edge to reach r.)
We may thus do DFS starting at r. We know that all
vertices reachable from r will belong to the tree rooted at r.
So we just check if the DFS tree rooted at r contains all of
V. If yes, then all vertices can be reached from r. If no, then
there is no vertex from which all vertices in V can be
reached. The total running time involves two runs of DFS
(one for topological sorting and one for checking
reachability from r thus the total running time is O(|V | +
|E|).
For general G (V, E) we first find the strongly connected
components of G and the component graph GSCC(VSCC,
SCC
E ). This can be done in O(|V | + |E|) using DFS. It is now
obvious that, since GSCC is acyclic, there exists a vertex v
V from which all other vertices are reachable if and only if
all of VSCC can be reached from the vertex r VSCC that is
first in a topological sorting of VSCC. The approach involves
a constant number of DFS calls, so the total running time is
O(|V | + |E|).
Problem 4, Dynamic Programming
Let G (V, E), V = {1, 2, . . . , n}, be a directed acyclic graph
given in adjacency list representation and in topologically
sorted order (that is, if i j E then i < j.) Describe an
O(|V | + |E|) time algorithm that finds the length of the
longest path from 1 to n. If there is no path from 1 to n then
your algorithm should output Nil. Justify correctness and
running time of your algorithm.
Hint: Consider finding the length of the longest path from
every vertex k to n, 1 k n.
Answer:
Let L(k) be the length of the longest path from node k to
node n, 1 k n.
L(n) = 0 and if, for some k < n, there is no path from k to n
then L(k) = Nil.
Suppose that, for some k n, L(j) has been correctly
computed for all j > k.
Since the graph is acyclic and presented topologically
sorted order, all edges out of k (which are the possible first
steps of a path from k to n) are of the form k j, j > k.
So we can update L(k) by looking at all of ks neighbors,
say j, and the corresponding L(j)s:
L(k) =

Nil,
,

if () = Nil for all E


if () 6 = Nil for some E

x = max{1 + L(j) : k j E and L(j) 6= Nil}


The memorization algorithm is then straightforward:
Initialization: L(n) := 0; for all 1 k n set L(k) := Nil;
Main Loop:
for k := (n 1) down to 1
for all j Adj(k)
if L(j) Nil
then L(k) :=
1 + L j ,
if L(k) = Nil
max L k , 1 + L j , if L(k) Nil
Each vertex is examined once in initialization and in the
first line of the main loop. and each edge is examined once
in the second line of the main loop. Thus the running time
is O(|V | + |E|).
Problem 1: Algorithm Correctness
An undirected graph G (V, E) is called bipartite if and only
if there is a partition of the vertices V to Vleft and Vright (i.e.
Vleft Vright = V and Vleft Vright = ) such that all edges in
E have one endpoint in Vleft and the other endpoint in Vright.
An undirected graph G (V, E) is called near bipartite if and
only if there exists an edge e E such that removing e
results in a bipartite graph:
G (V, E \ {e}) is bipartite.
Does the following algorithm correctly check if a graph
G (V, E) is near bipartite? If yes then give a short
explanation. In no then give a counter-example.
STEP 1: Use DFS and color vertices red and blue (the root
of DFS tree is colored red, and the color of every other
node is the opposite than the color of his parent in DFS.)
STEP 2: Look at the non-tree edges. If there are more than
one non-tree edges with endpoints of same color then the
graph is not near-bipartite. If there is at most one edge with
endpoints of same color then the graph is near-bipartite.
Answer:

False. Counter-example: G has vertices a, b, c, d and edges


{a, b}, {b, c}, {b, d}, {c, a} and {d, a}.
If DFS starts at a, then the DFS tree is a b, c b and d
b, coloring a red, b blue, and both c and d red. This
results in two edges with endpoints having the same color,
namely {c, a} and {d, a}. However, G is near bipartite,
because removing the edge {a, b} breaks all odd cycles and
leaves a bipartite graph.
Notes from reading CLRS:
GRAPHS:
Nesting of descendants intervals: Vertex v is a
proper descendant of vertex u in the depth-first
forest for a (directed or undirected) graph G if and
only if u.d < v.d < v.f < u.f.
Classification of edges:
1. Tree edge (u,v) if v was first discovered by
exploring (u,v).
2. Back edge (u,v) if connected u to ancestor v.
(loops)
3. Forward edge (u,v) connecting u to descendant v.
4. Cross edge are all other edges.
In DFS of an undirected graph G, every edge of G is
either a tree edge or a back edge.
Topological Sort: of a DAG is a linear ordering of
all its vertices such that if G contains an edge (u,v),
then u appears before v in the ordering.
1. Call DFS (G) to compute finishing times v.f for
each vertex v.
2. As each vertex is finished, inserted it onto front
of linked list.
3. Return the linked list of vertices.
Topological sort: for any edge (u,v) in the DAG,
we have v.f < u.f.
Strongly connected component: of a DAG G=(V,
E) is a maximal set of vertices C V such that for
every pair of vertices u and v in C, we have both u
v and v u; that is, vertices u and v are
reachable from each other.
1. Call DFS (G) to compute the finishing times u.f
for each vertex u
2. Compute GT
3. Call DFS (GT), but in the main loop of DFS,
consider the vertices in order of decreasing
u.f (as computed in line 1)
4. Output the vertices of each tree in the depthfirst forested formed in line 3 as a separate
SCC.
5. Creating GT takes O(V + E).
6. Let C and C be distinct SCC in a directed graph. Let
u, v C, let u, v C, and supposed that G
contains a path u u. Then G cannot also contain
a path v v.
7. Let C and C be distinct SCC in a directed graph.
Suppose that there is an edge (u,v) E, where u C
and v C. Then f(C) > f(C). [f is finishing time]

Solutions Manual Examples:


Depth First Search Connected Components
22.3-12: Show that we can use a depth-first search of an
undirected graph G to identify the connected components of
G, and that the depth-first forest contains as many trees as
G has connected components. More precisely, show how to
modify depth-first search so that it assigns to each vertex v
as integer label v.cc between 1 and k, where k is the number
of connected components of G, such that u.cc = v.cc if and
only if u and v are in the same connected component.

This DFS increments a counter each time DFS-VISIT is called to grow a new tree in the DFS
forest. Every vertex visited (and added to the tree) by DFS-VISIT is labeled with that same
counter value. Thus u.cc = v.cc if and only if u and v are visited in the same call to DFS-VISIT
from DFS, and the final value of the counter is the number of calls that were made to DFS-VISIT
by DFS. Also, since every vertex is visited eventually, every vertex is labeled. Thus all we need to
show is that the vertices visited by each call to DFS-VISIT from DFS are exactly the vertices in
one connected component of G.
All vertices in a connected component are visited by one call to DFS-VISIT from DFS:
Let u be the first vertex in component C visited by DFS-VISIT. Since a vertex becomes nonwhite only when it is visited, all vertices in C are white when DFS-VISIT is called for u. Thus,
by the white-path theorem, all vertices in C become descendants of u in the forest, which means
that all vertices in C are visited (by recursive calls to DFS-VISIT) before DFS-VISIT returns to
DFS.
All vertices visited by one call to DFS-VISIT from DFS are in the same connected component:
If two vertices are visited in the same call to DFS-VISIT from DFS, they are in the same
connected component, because vertices are visited only by following paths in G (by following
edges found in adjacency lists, starting from some vertex)

Top. Sorting Undirected Graph contains Cycle?


An undirected graph is acyclic (i.e., a forest) if and only if a DFS yields no back edges.
If theres a back edge, theres a cycle.
If theres no back edge, then by Theorem 22.10, there are only tree edges. Hence, the
graph is acyclic.
Thus, we can run DFS: if we find a back edge, theres a cycle.
Time: O(V). (Not O(V + E)!)
If we ever see |V| distinct edges, we must have seen a back edge because in an acyclic
(undirected) forest,
|E| |V| - 1.

Floyd Warshall Algorithm:

Prims & Kruskals:

Single Source Shortest Path Reading:

Directed Acyclic Graphs Shortest Path (G, w, s):


1. Topologically sort the vertices of G
2. INITIALIZE-SINGLE-SOURCE (G,s)
3. For each vertex u, taken in topologically sorted order:
for each vertex v G.Adj[u]: RELAX(u, v, w)

RELAX(u, v, w):
1. If v.d > u.d + w(u, v)
v.d = u.d + w(u, v)
v.pi = u
RULES of shortest paths:
Given a weighted, directed graph with weight function w: ER, let p = <v0, v1, , vk>
be a shortest path from vertex v0 to vertex vk and, for any i and j such that 0 I j k,
let pij = <vi, vi+1, , vj> be the subpath of p from vertex vi to vj.
Shortest path cannot contain a neg-weight cycle, since removing the cycle from the
path produces a path with the same source and destination vertices and a lower path
weight.
Can have 0-weight cycles we can remove a 0-weight cycle from any path to produce
another path whose weight is the same. Thus if there is a shortest path from a source
vertex s to a destination vertex v that contains a 0-weight cycle, then there is another
shorest path from s to v without this cycle. As long as a shortest path has 0-weight
cycles, we can repeatedly remove these cycles from the path until we have a path that
is cycles free.

OLD HOMEWORKS:

MST


MST Properties lowest cost
Suppose to the contrary that there is no MST for the graph Gwhich includes the edge (u, v).
Let T be any MST of G. By our assumption, T does not contain (u, v). Adding (u, v) to Twill
introduce a cycle since T is a free tree. This cycle involves (u, v). Therefore there is a path
from v to u that does not pass through this edge. This means that there exists another
edge (u', v') in T such that u' U and v' V - U.

Вам также может понравиться