Data Structures & AlgorithmsVery hardICPC regional · matrix power on graphs
Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from vertex 0 to vertex 3? Use the code below.
Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from vertex 0 to vertex 3? Use the code below.
A = [[0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0]]
def mul(X, Y):
return [[sum(X[i][k] * Y[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
P = A
for _ in range(2):
P = mul(P, A)
print(P[0][3])What is printed?- A. 2
- B. 0
- C. 3
- D. 1
Correct answer: D. 1
The only 3-edge walk is 0 to 1 to 2 to 3. The two-edge walks 0-1-3 and 0-2-3 end at 3 too early, so the matrix power A^3 gives 1.
More Coding Interview Problems questions
- Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and…
- Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices…
- Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'. python def lcssub(a, b): best = 0 dp =…
- Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'? python s = 'banana' p = 'ana' print(sum(1 for i…
- Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last…
- Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start…