DAA_MOD_3
DAA_MOD_3
4.Modify the all-pairs shortest path algorithm to detect negative-weight cycles in a weighted graph.
5. For the money change problem with n coins of values v1 = 1, v_2, ……, vn , and a target
amount X :
7.For a directed graph G = (V, E) with adjacency matrix M , devise a dynamic programming
algorithm to compute the reflexive and transitive closure M^*, where M^*(u, v) = 1 if u = v or
there is a path from u to v , and 0 otherwise. (Hint: Adapt the Floyd-Warshall algorithm.)
8. For a directed graph G = (V, E) , compute the n X n distance matrix D , where D(u, v) is the
shortest path length (in number of edges) from u to v , or 0 if no path exists. (Hint: Modify the
Floyd-Warshall algorithm.)
9. For a directed acyclic graph (DAG) with vertices u and v (both with zero indegree and
outdegree):
10. Given n cities and their intercity distances, design an algorithm to find the minimum tour length
for a cycle visiting each city exactly once (except the starting city). Analyze its time complexity and
determine if it can be solved in O(n^2 2^n) .
Problem:
Modify an all-pairs shortest path algorithm (e.g., Floyd-Warshall) to detect if the graph contains a
negative-weight cycle.
o D[i][j] = 0 if i == j,
o D[i][j] = ∞ otherwise.
o After the algorithm, if any D[i][i] < 0, then vertex i is part of a negative-weight cycle.
Time Complexity:
Problem:
Given coins v₁=1, v₂, ..., vₙ and amount X, find the minimum number of coins to make X.
DP Approach:
3. Transition:
For each x from 1 to X,
dp[x] = min(dp[x], dp[x - vᵢ] + 1) for all coins vᵢ ≤ x.
code
dp = [float('inf')] * (X + 1)
dp[0] = 0
if coin <= x:
Problem:
Given adjacency matrix M of a directed graph, compute M* where M*[u][v] = 1 if u = v or a path
exists from u to v.
Pseudocode:
def transitive_closure(M):
n = len(M)
for k in range(n):
for i in range(n):
for j in range(n):
return closure
Time Complexity:
Problem:
Compute an n × n matrix D where D[u][v] = shortest path length (edge count) from u to v, or 0 if no
path exists.
Solution:
1. Initialize D where:
o D[i][j] = 0 if i == j,
o D[i][j] = ∞ otherwise.
Time Complexity:
• O(V³).
(a) DP Algorithm
Problem:
Find the longest path from u to v in a DAG where u and v have zero indegree and outdegree,
respectively.
Solution:
Pseudocode:
python
Copy
Download
top_order = topological_sort(graph)
dp = [-inf] * len(graph)
dp[u] = 0
return dp[v]
Problem:
Find the minimum tour length visiting all n cities exactly once (cycle).
3. Transition:
For each subset mask and city u, update:
o dp[mask | (1 << v)][v] = min(dp[mask | (1 << v)][v], dp[mask][u] + dist[u][v]).
Time Complexity:
Pseudocode:
python
Copy
Download
def tsp(dist):
n = len(dist)
for u in range(n):
for u in range(n):
for v in range(n):
Summary:
Practical Applications
1. A motorist seeks the shortest route from Kolkata to Mumbai using a roadmap with distances
between adjacent intersections. Describe how to find the shortest route.
2. Given n integers in the range 0 ….. K , partition them into two subsets to minimize the absolute
difference |S1 - S2| , where S1 and S2 are the sums of the subsets.
3. For an ordered sequence of n cities with pairwise distances, partition the cities into two
subsequences (not necessarily contiguous) such that person A visits the first subsequence and
person B visits the second, both in order, starting at their respective first cities. Minimize the total
distance traveled by A and B.
Problem:
Find the shortest path between two cities (Kolkata and Mumbai) on a roadmap where distances
between adjacent intersections are known.
• Algorithm Steps:
1. Initialize distances:
3. Relaxation Step:
4. Termination:
Example:
Suppose the roadmap has intersections:
Time Complexity:
Problem:
Given n integers in [0, K], partition them into two subsets S1 and S2 such that |sum(S1) - sum(S2)| is
minimized.
• Key Insight:
• DP Approach:
Algorithm Steps:
1. DP Table Definition:
2. Base Case:
3. Fill DP Table:
Time Complexity:
• O(n × K) (pseudo-polynomial).
3. Partitioning Ordered Cities Between Two Travelers for Minimum Total Distance
Problem Restatement
Given an ordered sequence of n cities with pairwise distances, partition them into two
subsequences (A and B) such that:
Key Observations
1. Order Matters: Since cities must be visited in their original sequence, we cannot rearrange
them.
2. Partitioning Choices: At each step, we decide whether the next city goes to A or B.
3. Optimal Substructure: The best assignment for the first k cities depends on the last cities
assigned to A and B.
• Final Answer: The minimum value among all dp[i][n] and dp[n][j].
Algorithm Steps
1. Initialize dp as a 2D array filled with ∞, except dp[0][0] = 0.
Example
Cities: [A, B, C]
Distances: A→B = 2, B→C = 3
Possible Partitions:
1. A = [A, B, C], B = []
o A: A→C (assume direct distance = 5 if given, else invalid since order matters).
o B: B (distance = 0) → Total = 5 + 0 = 5.
3. A = [A], B = [B, C]
o A: A (distance = 0).
DP Table Snapshots:
• dp[0][0] = 0 (start).
• Assign A to A: dp[1][0] = 0 + 0 = 0.
• Assign B to B: dp[0][2] = 0 + 2 = 2.
• Assign C to B: dp[0][3] = 2 + 3 = 5.
• Assign C to A: dp[3][2] = 0 + 5 = 5.
Pseudocode
python
Copy
Download
n = len(cities)
dp[0][0] = 0
k = max(i, j) + 1
if k > n:
continue
# Assign to A
if i != 0:
else:
# Assign to B
if j != 0:
else:
Key Takeaways
• The problem is solved by DP with state tracking of the last cities assigned to A and B.
• Initialization and transitions must handle cases where a traveler hasn’t started yet
(i=0 or j=0).
Dijkstra’s Algorithm and Variants
1. Provide an example of a directed graph with negative-weight edges where Dijkstra’s algorithm fails
to produce correct shortest paths.
5. For a weighted directed graph where edges leaving the source s may have negative weights, but
other edges are non-negative and no negative-weight cycles exist, prove that Dijkstra’s algorithm
correctly finds shortest paths from s.
6. Evaluate the efficiency of Dijkstra’s algorithm using two different graph representations.
8. Find the shortest paths from vertex 1 to all other vertices in a given graph using Dijkstra’s
algorithm.
9. Assign edge weights to a graph such that Dijkstra’s algorithm fails to find the correct shortest path
from s to t .
11. Prove that if all edge weights in a graph are positive, any subset of edges connecting all vertices
with minimum total weight is a tree. Provide an example showing this does not hold for non-positive
weights.
13. Develop a simplified version of Dijkstra’s algorithm that computes only the distances from a given
vertex to all others, using a weight matrix representation.
14. Describe Dijkstra’s algorithm for finding shortest paths with a suitable example.
Solutions :
1. Provide an example of a directed graph with negative-weight edges where Dijkstra’s algorithm
fails to produce correct shortest paths.
• A → C (weight = 1)
• C → B (weight = –2)
Dijkstra’s Output: Chooses A → B directly with weight 4, ignoring negative update via C.
Failure Reason: Dijkstra assumes once a node is visited with the smallest cost, it won’t get better—a
condition violated with negative weights.
Steps:
Example: Graph:
Start: A
Distances: A=0, B=∞, C=∞
Step 1: Visit A → B=2, C=5
Step 2: Visit B → C=2+1=3 (better than 5)
Result: A→B=2, A→C=3
(a) Does Dijkstra’s algorithm work for graphs with negative weights?
No. Dijkstra’s algorithm assumes that once a node is visited, its shortest path is final, which fails with
negative weights.
5. For a graph where only edges leaving the source may be negative (others non-negative), prove
Dijkstra still works.
Proof Sketch:
• Once source vertex s processes its neighbors, negative weights may temporarily mislead.
• But since all subsequent edges are non-negative, no better path can reduce the cost further.
8. Find shortest paths from vertex 1 to all others using Dijkstra’s algorithm.
This depends on a provided graph. If you upload or describe it, I’ll solve it with steps.
9. Assign edge weights so that Dijkstra fails to find the correct shortest path from sss to ttt.
Use:
Correct path: s → b → a → t = 1 – 5 + 1 = –3
Dijkstra's path: s → a → t = 10 + 1 = 11
11. Prove that if all edge weights are positive, any subset of edges connecting all vertices with
minimum total weight is a tree.
Proof Sketch:
• If it connects all nodes and has minimum cost, no cycles are allowed (cycles add unnecessary
cost).
14. Describe Dijkstra’s algorithm for finding shortest paths with a suitable example.
Steps of Dijkstra’s Algorithm:
1. Initialize:
o Set the distance to the source node as 0 and to all other nodes as ∞.
o Mark all nodes as unvisited. Set the source as the current node.
o If the calculated distance of a node is less than the known distance, update it.
4. Select the unvisited node with the smallest tentative distance as the new current node,
and repeat from step 2.
5. Repeat until all nodes are visited or the smallest tentative distance among the unvisited
nodes is ∞.
Example:
Consider a graph with 5 vertices (A, B, C, D, E) and the following weighted edges:
/|\
4 1 2
/ | \
B C D
\ | /
5 3
Edge weights:
• A–B: 4
• A–C: 1
• A–D: 2
• B–E: 5
• C–E: 3
• D–E: 3
Goal: Find the shortest path from A to all other nodes.
Step-by-Step Execution:
A 0 —
B ∞ —
C ∞ —
D ∞ —
E ∞ —
1. Start at A:
• A → B = 4 → update B = 4
• A → C = 1 → update C = 1
• A → D = 2 → update D = 2
Updated distances:
• B: 4, C: 1, D: 2, E: ∞
• C → E = 3 → A to C to E = 1 + 3 = 4 → update E = 4
3. Next: D
4. Next: B
• B → E = 5 → A to B to E = 4 + 5 = 9 (not better)
• A: 0
• B: 4
• C: 1
• D: 2
• E: 4
Shortest Paths:
• A to B: A → B
• A to C: A → C
• A to D: A → D
• A to E: A → C → E
Time Complexity:
2.Starting with eight singleton sets {1}, {2}, ……., {8} , each represented by a single-node tree, apply
the union-find algorithm to compute the tree representation after the operations:
a. union(1, 2)
b. union(3, 4)
c. union(5, 6)
d. union(7, 8)
e. union(1, 3)
f. union(5, 7)
g. find(1)
h. find(5)
i. find(7).
4. Prove that for a node x in a tree resulting from union-find operations with union by rank and path
compression, the rank of x is an upper bound on its height.
5. Show that if all unions occur before finds in a union-find sequence with union by rank and path
compression, the time complexity is optimized.
7. Prove that the weighting rule guarantees a tree height of O(log n).
8. For a tree resulting from union-find with union by rank and path compression, prove that the ranks
of nodes on the path from a leaf to the root form a strictly increasing sequence.
2. Apply union-find to sets {1}, {2}, ..., {8} with these operations:
Operations:
a. union(1, 2)
b. union(3, 4)
c. union(5, 6)
d. union(7, 8)
e. union(1, 3)
f. union(5, 7)
g. find(1)
h. find(5)
i. find(7)
Initial sets:
{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}
• a. {1,2}
• b. {3,4}
• c. {5,6}
• d. {7,8}
• e. {1,2,3,4}
• f. {5,6,7,8}
• {1,2,3,4}
• {5,6,7,8}
4. Prove that the rank of a node xxx is an upper bound on its height (with union by rank and path
compression).
• Rank is used to approximate the height.
• During union by rank, we attach the smaller tree under the root of the larger tree.
5. Show that if all unions occur before finds, time complexity is optimized.
• When find operations are performed after all union operations, the structure is already near
flat due to path compression.
• This results in amortized time per operation: O(α(n)) — very close to constant.
• When we always attach the smaller tree under the larger one, the number of nodes at each
level doubles at most.
8. Prove that ranks of nodes on path from a leaf to root are strictly increasing.
o each successive node has higher rank than the one before.
o Total cost is O(nlogn) (logarithmic time per union due to increasing list size).
10. If the set with more elements gives name in each union, prove total cost is O(nlogn).
11.
• Detect cycles.
• Combines:
o Union by rank/size
o Path compression
Vertices: {a, b, c, d, e, f, g, h, i, j, k}
Edges:
(d, i), (f, k), (g, i), (b, g), (a, h), (i, j),
(d, k), (b, j), (d, f), (g, j), (a, e), (i, d)
Apply union-find:
1. union(d, i)
2. union(f, k)
3. union(g, i) → connects g, d, i
4. union(b, g) → adds b
5. union(a, h)
6. union(i, j)
7. union(d, k) → f, k added to d, i, g
8. union(b, j)
9. union(d, f) – redundant
10. union(g, j) – redundant
11. union(a, e)
• {a, e, h}
• {b, d, f, g, i, j, k}
6. Prove that a flow in a network with infinite-capacity edges (from multiple sources/sinks
conversion) has finite value if the original edges have finite capacity.
7. Convert a flow network with multiple sources (producing p_i units) and sinks (consuming qj units)
into a single-source, single-sink network to find a flow satisfying the constraints.
9. Show that the Ford-Fulkerson algorithm remains correct if the residual network disallows edges
into the source s .
10.For two flows f and f' , determine if the augmented flow f f' satisfies flow conservation and
capacity constraints.
11.Show how to compute a maximum flow using at most |E| augmenting paths.
12. Determine the edge connectivity of an undirected graph by running maximum-flow algorithms on
at most |V| flow networks, each with O(V) vertices and O(E) edges.
13.For a flow network with an edge (v, s) having flow f(v, s) = 1 , prove there exists another
flow f' with f'(v, s) = 0 and equal value. Provide an O(E) -time algorithm to compute f' .
14. Modify the capacities of a flow network G to create a new network G' where any minimum cut
in G' has the smallest number of edges among minimum cuts in G .
6. Prove that a flow in a network with infinite-capacity edges (from multiple sources/sinks
conversion) has finite value if original edges have finite capacity.
Proof Sketch:
o Add edges from a super source to original sources and from sinks to a super sink.
• So, the overall maximum flow is finite since it depends on original finite-capacity edges.
9. Show that Ford-Fulkerson remains correct if residual network disallows edges into source sss.
10. For two flows f and f′, determine if augmented flow f+f′ satisfies conservation and capacity.
•
12. Determine edge connectivity of an undirected graph using at most ∣V∣ flow networks.
Steps:
3. Optimization:
o Pick one vertex and compute flow to all others: O(V) max-flow computations.
13. Given edge (v,s) with flow 1, prove there exists another flow f′ with f′(v,s)=0 and same total
flow.
Proof Idea:
Algorithm (O(E)):
14. Modify network G into G′ such that any minimum cut in G′ has the fewest edges among all
minimum cuts.
Approach:
• This transformation:
o Prioritizes cut capacity first, and minimizes edge count when capacities tie.
1. Define a graph.
4. Explain how to find the minimum number of edges to keep a graph connected.
10. Draw a complete graph with four nodes and all its spanning trees.
11. Explain why Kruskal’s algorithm always produces an optimal spanning tree.
12. Determine the running time of an unweighted shortest path algorithm using the path with the
fewest edges.
1. Define a graph.
A graph G=(V,E) is a mathematical structure consisting of:
• V: A set of vertices (or nodes).
Unique Paths Exactly one path between any two nodes Not necessarily
4. Explain how to find the minimum number of edges to keep a graph connected.
• For an undirected graph with n vertices, at least n−1edges are needed to keep it connected.
• If disconnected, find the number of connected components (c) and add c−1edges.
o Entry is:
• Useful for:
o Connectivity checks.
• Used for:
o Topological sort.
o Cycle detection.
10. Draw a complete graph with four nodes and all its spanning trees.
o 4 vertices, 6 edges.
• Each spanning tree will have exactly 3 edges connecting all 4 nodes without cycles.
11. Explain why Kruskal’s algorithm always produces an optimal spanning tree.
• Kruskal's algorithm selects the minimum-weight edge that does not form a cycle.
12. Determine the running time of an unweighted shortest path algorithm using the path with the
fewest edges.
• Time Complexity:
Graph analysis
6. Prove that the sum of vertex degrees in an undirected graph equals twice the number of edges.
7. Prove or disprove: A finite directed graph with each vertex having out-degree at least one contains
a directed cycle.
8. a. Show that a connected undirected graph with n vertices has at least n-1 edges, and those
with exactly n-1 edges are trees.
b. Find the minimum number of edges in a strongly connected digraph with n vertices and
describe its structure.
9. Prove the equivalence of the following for an undirected graph G with n vertices:
a. G is a tree.
c. There is exactly one simple path between any two distinct vertices.
a. Prove that the heaviest edge in any cycle does not belong to a minimum-cost spanning tree.
b. Show that any F -heavy edge in a forest F (subgraph of G ) does not belong to a minimum-cost
spanning tree.
6. Show that the number of spanning trees in an n -vertex complete graph can exceed 2^{n-1} - 2 .
• In an undirected graph, each edge contributes to the degree of two vertices (one at each
end).
• Then, the total sum of degrees is 2m, since each edge is counted twice (once for each vertex
it connects).
Proof:
• Since the graph is finite, we must eventually revisit a vertex, forming a cycle.
• Conclusion: Every finite directed graph with out-degree ≥ 1 has a directed cycle.
Proof:
• Minimum edges: A connected graph must have at least n−1 edges (otherwise, it would be
disconnected).
• Trees: If it has exactly n−1 edges and is connected, it cannot have cycles (since removing any
edge would disconnect it). Hence, it is a tree.
Proof:
We show (a) ⇒ (b) ⇒ (c) ⇒ (d) ⇒ (a).
• (a) ⇒ (b): A tree is connected and acyclic; removing any edge disconnects it.
• (c) ⇒ (d): Unique paths imply no cycles, and connectedness with n−1n−1 edges defines a
tree.
Proof:
• Prim’s algorithm grows the MST by always adding the lightest edge connecting the tree to a
new vertex.
• Since it never forms a cycle, the final result is a spanning tree of minimal cost.
Proof:
• Adding an edge ee between two vertices u and v introduces a cycle because T already has a
unique path between u and v.
• The cycle is unique because any other cycle would imply multiple paths between uu and vv,
contradicting tree properties.
Proof: