Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Competitive Programming

BFS and DFS

Week 5 Assignment
1. Say while implementing DFS, you add a time variable T and initially set it to 0. T is incremented every
time a vertex in the graph is visited. For vertex v, let Pre(v) = T, right before we mark the vertex as
visited and increase T. Post(v) is T when all adjacent vertices of v are visited.
Consider two vertices A and B.
(a) If Post(A) < Pre(B), then A and B are in the same connected component.
A. True B. False C. Can’t say
Solution

The answer is: Option (C).

It could be that both are on different sides of a tree or they could also be part of different
connected components.

(b) If Post(A) > Pre(B) and Post(A) < Post(B), then A and B are in the same connected component.
A. True B. False C. Can’t say
Solution

The answer is: Option (A).

If Post(A) > Pre(B) and Post(A) < Post(B), then that means A is visited while visiting B’s
neighbours and doing DFS on them. So A and B should be in the same connected compo-
nent.

(c) If Post(A) = Pre(A)+1, then A is an isolated vertex.


A. True B. False C. Can’t say
Solution

The answer is: Option (C).

It could be a isolated vertex, or a vertex with degree 1 or also a vertex where all of its
neighbours are already visited.

Page 2
2. Suppose you are given a tree having N vertices numbered from 1 to N in the form of adjacency list
adj list. You can do the following one operation on this tree as many times as possible:
→ Delete all vertices which have either 0 or 1 neighbours.
You need to determine after how many such operations on the given tree, all of its vertices will be
deleted.
Note: Tree is a connected and undirected graph which do not have any cycles.
(a) For the below given tree, after how many operations all of its vertices will be deleted?

Fig. 1: Tree having 11 vertices

Solution

The answer is: 4.

Consider the below operations:

Fig. 2: Operations on the Tree

Consider the following function for BFS:


function BFS (adj_list, root):
# distance: Array of length N in which dist[i] is the shortest distance
between root and vertex i

Page 3
distance := [INF, INF, INF, ..., INF]

distance[root] := 0

queue := Initialize empty queue for BFS


queue.append(root)

while := queue is not empty


s := queue.pop(0)

for := vertex in adj_list[s]


if := distance[vertex] == INF
distance[vertex] = distance[s] + 1
queue.append(vertex)

max(distance) := the maximum element of the distance array


return max(distance)
(b) Let’s not worry about the time complexity for now. Which of the following option will return the
minimum number of operations required to delete all vertices of the tree?
Note: min(array) returns the minimum element of the array, and max(array) returns the maxi-
mum element of the array.
A. ans := min[BFS (adj list, v) for all v ∈ vertex set of tree]
B. ans := max[BFS (adj list, v) for all v ∈ vertex set of tree]
C. ans := BFS (adj list, s) for any s ∈ vertex set of tree (Since the BFS function
will return same value for any vertex as root)
D. None of the above
Solution

The answer is: Option (A).

The given BFS function returns the maximum distance of any leaf from the given root. If
we choose the root such that the maximum distance between the root and any other vertex
is least, then this distance will be same as the minimum required operations to delete all
the elements. Because if we root the tree at some vertex such that it has minimum number
of different levels, the according to the given operation, in each operation we will delete
all vertices of the farthest level. So, number of minimum operations equals to number of
minimum levels.

(c) What is the time complexity and space complexity of the above given BFS function on tree with N
vertices?
A. Time Complexity := O(N 2 ), Space Complexity := O(N 2 )
B. Time Complexity := O(N ), Space Complexity := O(N )
C. Time Complexity := O(N ), Space Complexity := O(N 2 )
D. Time Complexity := O(N 2 ), Space Complexity := O(N )

Page 4
Solution

The answer is: Option (B).

The time complexity of BFS is O(V + E) as during the visit of every vertex every edge is
visited exactly once. Since tree has N vertices and N − 1 edges, time complexity will be
O(N ). The maximum size the queue can reach is N and the distance array also uses O(N )
space, so the space complexity will be O(N ).

Page 5
3. Consider the problem Longest Trail
You are a map of islands, V and the distance between different pair of islands. Each island is uniquely
identified by a number between 1 and |V |. Each island is connected to another island either directly or
through a series of islands Ii , Ii+1 , ...., Ij . However, there is no cycle between any two islands. There
is only one boat available for traversing between the islands. Your trip to these islands only allows for
one exchange between any pair of islands: if you start from island Ii , and stop at Ij , you cannot use the
boat further, your trip ends. Additionally, you can only fill the fuel in the boat once for the whole trip.
Your task is to find the maximum amount of fuel that you should fill your boat with, so you can cover
the maximum possible distance in your whole trip. Assume the boat mileage to be 1 unit per litre.

For example:
Consider the input of form (u , v | dist(u, v)) u, v ∈ G
|V| = 3
1 , 2 | 3
2 , 3 | 4
The output should be : 7
(a) Answer either True or False: Consider the islands as vertices and add an edge between any pair
of islands that are connected directly. For any pair of islands that are not directly connected, there
are no edges. This graph is a tree.
Solution

The answer is: True

The resulting graph is circuit-free (as no islands are connected by a circular path). Addi-
tionally, every island (or vertex) is connected with every other island (or vertex). Hence,
the resulting graph is one connected component. By definition, a connected and circuit-free
graph is a tree. Hence the statement is true.

(b) What should be the output to the following input?


|V| = 8
1 , 2 | 8
2 , 3 | 10
3 , 4 | 7
8 , 7 | 11
3 , 7 | 12
7 , 5 | 6
6 , 7 | 13
Submission Format: If the maximum path length is 20, you should type 20 as your answer.
Solution

The answer is: 43

Page 6
4. Consider the problem Get Target Fluid!

You are given two jars J1 and J2 with capacity J1cap, J2cap respectively (in litres). Your task is to
measure out exactly x liters of water using J1 and/or J2 . The following operations are allowed:
• Empty either J1 or J2
• Fill either of the jugs with water to its maximum capacity
• Shift water from one jug to another till water level in the first jug is either zero or the second jug is
full
You are allowed to do these operations any number of times as you wish. Note that if it is possible to
retrieve x capacity of water using these operations, we shall have x liters of water in either J1 , J2 or
both at the end of the iterations.
For example:

J1cap = 6 , J2cap = 2 , x = 5
Output: False

(a) What will Get Target Fluid output for the following input?
J1cap = 10078 , J2cap = 9899 , x = 45
A. True
B. False
Solution

The answer is: Option (A)

(b) Consider the algorithm math attempt:


def can_retrieve(j1cap,j2cap,x):
if j1cap == x or j2cap == x or j1cap+j2cap == x:
return True
if Exp1:
return False
return Exp2 == 0
Note: % denotes mod operation

Page 7
Among the following options, select the most appropriate for Exp1 and Exp2.
A. Exp1 => j1cap < j2cap and j1cap<t
B. Exp1 => max(j1cap,j2cap)>t and j1cap%j2cap==0
C. Exp1 => j1cap+j2cap<t
D. Exp2 => t%hcf(j1cap,j2cap)
E. Exp2 => t%lcm(j1cap,j2cap)
F. Exp2 => lcm(j1cap,j2cap)%t
G. Exp2 => hcf(j1cap,j2cap)%t
H. Exp2 => hcf(j1cap-t,j2cap-t)
I. Exp2 => t%max(j1cap,j2cap)
Solution

The answer is: Options (C),(D)

A high level idea of the above algorithm can be given as follows:


If the sum of capacities of J1 and J2 is equal to the target capacity x, then we can trivially fill
up both jugs and get the desired amount. Similar claim follows if either of the jug capacities
equal to the target capacity. Now, the maximum amount of water we can retrieve from the
given setting is no greater than J1cap + J2cap, where J1cap, J2cap are the capacities of
J1 and J2 respectively. Therefore if J1cap+J2cap < x, no sequence of operations can help
in retrieval of x amount of fluid.
The idea is to break the capacity of both the jugs, individually, into the smallest units
possible. If n times the unit equal x, then we can claim that it is possible to retrieve
x litres of fluid (where n ∈ N). The problem now reduces to finding the smallest
unit in which we can break up both of the capacities into the largest integers possible.
Clearly, hcf of both capacities gives an integer that divides J1cap and J2cap. Hence if
x is divisible by hcf(J1cap,J2cap), it is enough to claim that we can achieve x litres of fluid.

Food for thought: When we transfer/shift fluid from one jug to another, can we argue
that the net effect of transfer is always in terms of hcf of the two capacities?

Page 8

You might also like