Data Structures & AlgorithmsVery hardProduct company OA
Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make the graph strongly connected)?
Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make the graph strongly connected)?
import sys
sys.setrecursionlimit(10000)
n = 8
g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [3], 5: [4, 6], 6: [], 7: [6]}
idx, low, on, st, comp, cnt, t = {}, {}, set(), [], {}, 0, 0
def dfs(u):
global t, cnt
idx[u] = low[u] = t; t += 1; st.append(u); on.add(u)
for v in g[u]:
if v not in idx: dfs(v); low[u] = min(low[u], low[v])
elif v in on: low[u] = min(low[u], idx[v])
if low[u] == idx[u]:
while True:
w = st.pop(); on.discard(w); comp[w] = cnt
if w == u: break
cnt += 1
for u in range(n):
if u not in idx: dfs(u)
indeg, outdeg = [0] * cnt, [0] * cnt
for u in g:
for v in g[u]:
if comp[u] != comp[v]: outdeg[comp[u]] += 1; indeg[comp[v]] += 1
src = sum(1 for c in range(cnt) if indeg[c] == 0); snk = sum(1 for c in range(cnt) if outdeg[c] == 0)
print(cnt, src, snk, max(src, snk) if cnt > 1 else 0)- A. 5 2 2 2
- B. 5 3 2 3
- C. 4 3 2 3
- D. 6 3 2 5
Correct answer: B. 5 3 2 3
SCCs: {0, 1, 2}, {3, 4}, {5}, {6}, {7}. In the condensation, {0, 1, 2}, {5}, {7} have no incoming edges (3 sources) and {3, 4}, {6} have no outgoing edges (2 sinks). For a condensation with more than one node, the minimum number of added edges is max(sources, sinks) = 3 – each source needs an incoming and each sink an outgoing edge, and one edge can serve a sink and a source together. 2 forgets that sources and sinks must both be fixed. O(V + E).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…
- Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed? python…
- Match each recurrence to its tight bound: (P) T(n) = 2T(n/2) + n log n (Q) T(n) = 2T(n/2) + n / log n (R) T(n) = T(n/2) + log n (S) T(n) =…
- A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of…
- Which loop nests perform Θ(n log n) executions of work()? c / A / for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work(); / B / for…