Multistage Algorithm:
Define the problem: We have a directed graph with n vertices and m edges, where each edge has a weight associated with it. The graph is divided into k stages, where the first stage contains only the source node and the last stage contains only the sink node. Our task is to find the minimum cost path from the source to the sink.
Define the subproblems: We will define subproblems for each stage of the graph. Let's say we are at stage i. We need to find the minimum cost path from the source to each node in stage i. We will define an array M[i][j] to store the minimum cost of reaching node j in stage i.
Initialize the base case: We will start with the last stage of the graph, which contains only the sink node. We set M[k][j] = 0 for all nodes j in stage k.
Recurrence relation: For each stage i, we will calculate the minimum cost of reaching each node j in stage i by considering all outgoing edges from j to nodes in stage i+1. We will use the following recurrence relation:
M[i][j] = min(M[i+1][k] + cost(j, k)) for all nodes k in stage i+1, where cost(j, k) is the weight of the edge from node j to node k.
Final solution: The minimum cost path from the source to the sink can be found by starting at the source node and following the path with the minimum cost at each stage until we reach the sink node.
0/1 Knapsack:
Define the problem: We are given n items with weights w[1], w[2], ..., w[n] and values v[1], v[2], ..., v[n] respectively. We also have a knapsack of capacity W. Our task is to choose a subset of items that can be put into the knapsack such that the total weight is less than or equal to W and the total value is maximized.
Define the subproblems: We will define subproblems for each item i and weight w. Let's say we are at item i and weight j. We need to find the maximum value that can be obtained using items 1 to i and a knapsack of capacity j. We will define an array K[i][j] to store the maximum value.
Initialize the base case: We will start with the first item, i.e., i=1. We set K[1][j] = v[1] if w[1] <= j and 0 otherwise.
Recurrence relation: For each item i and weight j, we have two choices: either include item i or exclude item i. We will use the following recurrence relation:
K[i][j] = max(K[i-1][j], K[i-1][j-w[i]] + v[i])
where K[i-1][j] represents the maximum value obtained without including item i and K[i-1][j-w[i]] + v[i] represents the maximum value obtained by including item i.
Final solution: The maximum value that can be obtained using items 1 to n and a knapsack of capacity W can be found by looking at K[n][W].
No comments:
Post a Comment