0% found this document useful (0 votes)
9 views6 pages

Mahim DSA 10

The document outlines three lab experiments focusing on dynamic programming and heuristics. It includes implementations for the 0/1 Knapsack problem, N-Queens problem using branch and bound, and Hamiltonian Cycle problem using a greedy heuristic. Each section provides objectives, tasks, example inputs, expected outputs, and corresponding code implementations.

Uploaded by

swastikkx69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Mahim DSA 10

The document outlines three lab experiments focusing on dynamic programming and heuristics. It includes implementations for the 0/1 Knapsack problem, N-Queens problem using branch and bound, and Hamiltonian Cycle problem using a greedy heuristic. Each section provides objectives, tasks, example inputs, expected outputs, and corresponding code implementations.

Uploaded by

swastikkx69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

DSA(UNC401)

Lab Experiment-10
Dynamic Programming and Heuristics
Submitted by:
Name-Mahim Dixit Roll no.-102206250 Group-3EC1

Q1: 0/1 Knapsack Problem Using Dynamic Programming


Objective: To understand and implement the dynamic programming
approach for solving the 0/1 knapsack problem, where the goal is to
select items such that the total value is maximized without exceeding the
knapsack’s capacity and without taking fractional parts of items.
Tasks:
1. Implement the 0/1 knapsack problem using bottom-up dynamic
programming.
2. Input the weights and values of items, and the maximum capacity of the
knapsack.
3. Calculate the maximum total value that can be obtained.
4. Print the selected items and the final value.
Example Input:
• Weights: [10, 20, 30]
• Values: [60, 100, 120]
• Capacity: W = 50
Expected Output:
• Max Value: 220 (Items 2 and 3)

CODE:
#include <iostream>
#include <vector>
using namespace std;

void solKnap(int maxCap, vector<int>& weights, vector<int>& values, int itemCount) {


vector<vector<int>> dp(itemCount + 1, vector<int>(maxCap + 1, 0));

for (int i = 1; i <= itemCount; i++) {


for (int cap = 1; cap <= maxCap; cap++) {
if (weights[i - 1] <= cap){
dp[i][cap] = max(values[i - 1] + dp[i - 1][cap - weights[i - 1]], dp[i -
1][cap]);
} else {
dp[i][cap] = dp[i - 1][cap];
}
}
}

cout << "Max Value: " << dp[itemCount][maxCap] << endl;


cout << "Selected Items (1-based indices): ";
int cap = maxCap;
for (int i = itemCount; i > 0 && cap > 0; i--) {
if (dp[i][cap] != dp[i - 1][cap]) {
cout << i << " ";
cap -= weights[i - 1];
}
}
cout << endl;
}

int main() {
vector<int> weights = {10, 20, 30};
vector<int> values = {60, 100, 120};
int cap = 50;
int numberOfItems = weights.size();
solKnap(cap, weights, values, numberOfItems);
return 0;
}

OUTPUT:

Q2: N-Queens Problem Using Branch and Bound


Objective: To apply the branch-and-bound technique to efficiently solve the
N-Queens problem, ensuring no two queens threaten each other on the
board.
Tasks:
1. Implement the N-Queens solution using backtracking with branch-and-
bound to prune the search space.
2. Input the size of the board (N).
3. Return one valid arrangement where each queen is placed in a different
row and column without diagonal conflicts.
4. Output the row indices of queens placed in each column.
Example Input: • N = 8
Expected Output: • One possible solution: [0, 4, 7, 5, 2, 6, 1, 3]

CODE:
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

bool isPositionSafe(int row, int col, vector<int>& queenPositions) {


for (int prevCol = 0; prevCol < col; prevCol++) {
int prevRow = queenPositions[prevCol];
if (prevRow == row || abs(prevRow - row) == abs(prevCol - col)) {
return false;
}
}
return true;
}

bool placeQueens(int col, int N, vector<int>& queenPositions) {


if (col == N) return true;

for (int row = 0; row < N; row++) {


if (isPositionSafe(row, col, queenPositions)) {
queenPositions[col] = row;
if (placeQueens(col + 1, N, queenPositions)) return true;
}
}
return false;
}

int main() {
int boardSize = 8;
vector<int> queenPositions(boardSize, -1);

if (placeQueens(0, boardSize, queenPositions)) {


cout << "One possible solution: ";
for (int i = 0; i < boardSize; i++) {
cout << queenPositions[i] << " ";
}
cout << endl;
} else {
cout << "No solution exists." << endl;
}

return 0;
}
OUTPUT:

Q3: Hamiltonian Cycle Problem Using Greedy Heuristic


Objective: To understand and implement the greedy heuristic (nearest
neighbor method) for solving the Hamiltonian Cycle Problem, where the
goal is to find a cycle that visits each city exactly once and returns to the
starting point.
Tasks:
1. Represent the cities and distances between them using a distance matrix.
2. Implement the nearest neighbor heuristic:
o Start from any city.
o At each step, move to the nearest unvisited city.
o Continue until all cities are visited.
o Return to the starting city to complete the cycle.
3. Calculate the total cost (distance) of the completed cycle.
4. Explore how this problem is related to the Traveling Salesman Problem
(TSP) from a Transform-and-Conquer perspective.
Example Input:
• Cities: A, B, C, D
• Distance Matrix:

Expected Output:
• Hamiltonian Cycle: A → B → C → D → A
• Total Cost: 1 + 2 + 5 + 4 = 12
CODE:
#include <iostream>
#include <vector>
#include <limits>

using namespace std;

int getNearestCity(int current, const vector<vector<int>>& distances, const vector<bool>&


visited) {
int nearestCity = -1;
int minDistance = numeric_limits<int>::max();

for (int i = 0; i < distances.size(); ++i) {


if (!visited[i] && distances[current][i] < minDistance) {
minDistance = distances[current][i];
nearestCity = i;
}
}
return nearestCity;
}

int main() {
vector<string> cityNames = {"A", "B", "C", "D"};
vector<vector<int>> distanceMatrix = {
{0, 1, 5, 4},
{1, 0, 2, 6},
{5, 2, 0, 3},
{4, 6, 3, 0}
};

int numberOfCities = cityNames.size();


vector<bool> visited(numberOfCities, false);
vector<int> tourPath;
int totalCost = 0;
int currentCity = 0;

visited[currentCity] = true;
tourPath.push_back(currentCity);

for (int i = 1; i < numberOfCities; ++i) {


int nextCity = getNearestCity(currentCity, distanceMatrix, visited);
if (nextCity != -1) {
totalCost += distanceMatrix[currentCity][nextCity];
visited[nextCity] = true;
tourPath.push_back(nextCity);
currentCity = nextCity;
} else {
// Should not happen in a complete graph
break;
}
}

totalCost += distanceMatrix[currentCity][tourPath[0]];
tourPath.push_back(tourPath[0]);
cout << "Hamiltonian Cycle: ";
for (int cityIndex : tourPath) {
cout << cityNames[cityIndex] << " ";
}
cout << endl;

cout << "Total Cost: " << totalCost << endl;

return 0;
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy