0% found this document useful (0 votes)
68 views

Lab Manual TT

The function takes in three arrays representing the heights of cylinders in three stacks. It returns the maximum height that all three stacks can be equalized to by removing cylinders from the top of stacks. This is done by removing cylinders from stacks until all three stacks are the same height, and returning that common height.

Uploaded by

Rohit Rohilla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Lab Manual TT

The function takes in three arrays representing the heights of cylinders in three stacks. It returns the maximum height that all three stacks can be equalized to by removing cylinders from the top of stacks. This is done by removing cylinders from stacks until all three stacks are the same height, and returning that common height.

Uploaded by

Rohit Rohilla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Apex Institute Technology (AIT)

Department of Computer Science Engineering

B.E. – CSE

SEMESTER : 4th (January-June 2024)

SUBJECT NAME : Technical Training LAB

SUBJECT CODE: 21-CSP-382

FACULTY : Ms. Neha Sharma


Syllabus
Unit-1 CO
Experiment-1 An array is a type of data structure that stores elements of the same type in
CO1,C
a contiguous block of memory. In an array,A , of size N , each memory location has some O2

unique index, (where ), that can be referenced as or Reverse an array of integers.

Experiment-2 A left rotation operation on an array of size n shifts each of the


CO3
array's elements 1 unit to the left. Given an integer, d, rotate the array that
many steps left and return the result.

Experiement-3 You have three stacks of cylinders where each cylinder has the same CO5

diameter, but they may vary in height. You can change the height of a stack by removing

and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the

same height. This means you must remove zero or more cylinders from the top of zero or

more of the three stacks until they are all the same height, then return the height.

Experiment- 4 Given a pointer to the head of a linked list, insert a new node before the CO4

head. The next value in the new node should point to head and the data value should be

replaced with a given value. Return a reference to the new head of the list. The head

pointer given may be null meaning that the initial list is empty.

Unit-2
Experiment-5 Given an undirected weighted connected graph, find the Really Special CO2

SubTree in it. The Really Special SubTree is defined as a subgraph consisting of all the

nodes in the graph and:


 There is only one exclusive path from a node to every other node.

 The subgraph is of minimum overall weight (sum of all edges) among all such subgraphs.

 No cycles are formed

To create the Really Special SubTree, always pick the edge with smallest weight.

Determine if including it will create a cycle. If so, ignore the edge. If there are edges of

equal weight available:

 Choose the edge that minimizes the sum u+v+wt where u and v are vertices and wt is the

edge weight.

 If there is still a collision, choose any of them.

Print the overall weight of the tree formed using the rules.

For example, given the following edges:

u v wt
1 2 2
2 3 3
3 1 5

Experiment-6 Complete the preOrder function in the editor below, which CO5
has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's

preorder traversal as a single line of space-separated values.

Experiment-7 There is a string, s, of lowercase English letters that is repeated CO3

infinitely many times. Given an integer,n , find and print the number of letter a's in the

first n letters of the infinite string.

Experiment-8 Given an array of integers and a target sum, determine the sum nearest CO1

to but not exceeding the target that can be created. To create the sum, use any element of
your array zero or more times.

Unit-3
Experiment-9 To implement traveling salesman problem using naive CO2
approach.

Experiment-10 Given a set of non-negative integers and a value sum, CO4


the task is to check if there is a subset of the given set whose sum is
equal to the given sum.

Experiment-1
Aim: An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an

array,A , of size N , each memory location has some unique index, (where ), that can be referenced as or Reverse an

array of integers.

Example

A=[1,2,3,4]

Return [3,2,1].

Function Description

Complete the function reverseArray in the editor below.

reverseArray has the following parameter(s):

 int A[n]: the array to reverse

Returns

 int[n]: the reversed array

Input Format

The first line contains an integer, N, the number of integers in A.

The second line contains N space-separated integers that make up A.

Constraints

 1<= N<=10^3

 1<= N<=10^4, where A[i] is the ith integer in A

Sample Input 1

Array: arr1432

4
1432
Sample Output 1
2341

Code:-
#include <iostream>
#include <vector>

using namespace std;

vector<int> reverseArray(vector<int> A) {
int start = 0;
int end = A.size() - 1;

// Swap elements from the start and end until they meet in the middle
while (start < end) {
swap(A[start], A[end]);
start++;
end--;
}

return A;
}

int main() {
int N;
cin >> N;

vector<int> A(N);

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


cin >> A[i];
}

vector<int> result = reverseArray(A);

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


cout << result[i] << " ";
}

return 0;
}
Steps to be done:
1. Open this link.( https://www.programiz.com/cpp-programming/online-compiler/)
2. Paste the above-given code and then click on run.
3. Input should be “Enter the size of array” (e.g. 3)
4. Show your conduct to the class teacher for evaluation.
Input:-

Output:-

Viva-Voce Questions
Q.1 What is an array?
Q.2 How are arrays different from other data structures?
Q.3Explain the concept of contiguous memory allocation in arrays
Q.4 How do you declare an array in C++?
Q.5 Can the size of an array be changed after declaration?

Experiment-2
Aim:- A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left.
Given an integer, d, rotate the array that many steps left and return the result.
Example

d=2

arr=[1,2,3,4,5]

After rotations, arr’=[3,4,5,1,2]

After rotations, .

Function Description

Complete the rotateLeft function in the editor below.

rotateLeft has the following parameters:

 int d: the amount to rotate by

 int arr[n]: the array to rotate

Returns

 int[n]: the rotated array

Input Format

The first line contains two space-separated integers that denote n, the number of integers, and d, the number of left

rotations to perform.

The second line contains n space-separated integers that describe arr[].

Constraints

 1<=n<=10^5

 1<=d<=n

 1<=a[i]<=10^6

Sample Input
54
12345
Sample Output

51234
Explanation

To perform d=4 left rotations, the array undergoes the following sequence of changes:

[1, 2, 3, 4, 5]->[2,3,4,5,1]->[3,4,5,1,2]->[4,5,1,2,3]->[5,1,2,3,4]

Code:-

#include <iostream>

#include <vector>

using namespace std;

// Function to left rotate an array by d steps

vector<int> rotateLeft(int d, const vector<int>& arr) {

int n = arr.size();

vector<int> rotatedArray(n);

// Perform left rotation

for (int i = 0; i < n; i++) {

int newIndex = (i + n - d) % n;

rotatedArray[newIndex] = arr[i];

return rotatedArray;
}

int main() {

int n, d;

cout << "Enter the size of the array and the number of left rotations (n d): ";

cin >> n >> d;

vector<int> arr(n);

cout << "Enter the elements of the array: ";

for (int i = 0; i < n; i++) {

cin >> arr[i];

vector<int> result = rotateLeft(d, arr);

cout << "Rotated Array: ";

for (int i = 0; i < n; i++) {

cout << result[i] << " ";

return 0;

Input:
Output:

Viva-Voce Questions
Q.1 What is an array?
Q.2 How are arrays different from other data structures?
Q.3Explain the concept of contiguous memory allocation in arrays
Q.4 How do you declare an array in C++?
Q.5 Can the size of an array be changed after declaration?
Experiment-3
Aim:- You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You

can change the height of a stack by removing and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you

must remove zero or more cylinders from the top of zero or more of the three stacks until they are all the same height,

then return the height.

Example

h1=[1,2,1,1]

h2=[1,1,2]

h3=[1,1]

There are 4,3 and 2 cylinders in the three stacks, with their heights in the three arrays. Remove the top 2 cylinders

from h1 (heights = [1, 2]) and from h2 (heights = [1, 1]) so that the three stacks all are 2 units tall. Return 2 as the

answer.

Note: An empty stack is still a stack.

Function Description

Complete the equalStacks function in the editor below.

equalStacks has the following parameters:

 int h1[n1]: the first array of heights

 int h2[n2]: the second array of heights

 int h3[n3]: the third array of heights

Returns

 int: the height of the stacks when they are equalized


Input Format

The first line contains three space-separated integers, n1, n2, and n3, the numbers of cylinders in stacks , , and . The

subsequent lines describe the respective heights of each cylinder in a stack from top to bottom:

 The second line contains n1 space-separated integers, the cylinder heights in stack 1. The first element is the top

cylinder of the stack.

 The third line contains n2 space-separated integers, the cylinder heights in stack 2. The first element is the top cylinder

of the stack.

 The fourth line contains n3 space-separated integers, the cylinder heights in stack 3. The first element is the top cylinder

of the stack.

Constraints

 0<n1,n2,n3<=10^5

 0<height of any cylinder<=100

Sample Input

STDIN Function
----- --------
534 h1[] size n1 = 5, h2[] size n2 = 3, h3[] size n3 = 4
3 2 1 1 1 h1 = [3, 2, 1, 1, 1]
432 h2 = [4, 3, 2]
1 1 4 1 h3 = [1, 1, 4, 1]
Sample Output

5
Explanation

Initially, the stacks look like this:


To equalize thier heights, remove the first cylinder from stacks 1, 2 and 3, and then remove the top two cylinders from

stack 3 (shown below).

The stack heights are reduced as follows:

1. 8-3=5

2. 9-4=5

3. 7-1-1=5

All three stacks now have height=5 , the value to return.

Code:-

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class EqualStacks {

public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {


// Reverse the stacks to simplify popping from the top
Collections.reverse(h1);
Collections.reverse(h2);
Collections.reverse(h3);

// Calculate cumulative heights for each stack


for (int i = 1; i < h1.size(); i++) {
h1.set(i, h1.get(i) + h1.get(i - 1));
}

for (int i = 1; i < h2.size(); i++) {


h2.set(i, h2.get(i) + h2.get(i - 1));
}

for (int i = 1; i < h3.size(); i++) {


h3.set(i, h3.get(i) + h3.get(i - 1));
}

// Find the common height by iterating until a common height is found or one of the stacks is empty
while (!h1.isEmpty() && !h2.isEmpty() && !h3.isEmpty() &&
!(h1.get(h1.size() - 1).equals(h2.get(h2.size() - 1)) && h2.get(h2.size() - 1).equals(h3.get(h3.size() - 1)))) {
if (h1.get(h1.size() - 1) >= h2.get(h2.size() - 1) && h1.get(h1.size() - 1) >= h3.get(h3.size() - 1)) {
h1.remove(h1.size() - 1);
} else if (h2.get(h2.size() - 1) >= h1.get(h1.size() - 1) && h2.get(h2.size() - 1) >= h3.get(h3.size() - 1)) {
h2.remove(h2.size() - 1);
} else {
h3.remove(h3.size() - 1);
}
}

// Return the common height if found, otherwise return 0


return (h1.isEmpty() || h2.isEmpty() || h3.isEmpty()) ? 0 : h1.get(h1.size() - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int n3 = scanner.nextInt();
List<Integer> h1 = new ArrayList<>(n1);
List<Integer> h2 = new ArrayList<>(n2);
List<Integer> h3 = new ArrayList<>(n3);

for (int i = 0; i < n1; i++) {


h1.add(scanner.nextInt());
}

for (int i = 0; i < n2; i++) {


h2.add(scanner.nextInt());
}

for (int i = 0; i < n3; i++) {


h3.add(scanner.nextInt());
}

int result = equalStacks(h1, h2, h3);


System.out.println("Maximum possible common height: " + result);
}
}

Input:

Output:

Viva-voce Questions:
Q.1 What is a stack?
Q.2 How can you implement a stack?
Q.3 What is the difference between a stack and a queue?
Q.4 Explain the operations that can be performed on a stack.
Q.5 Can a stack be implemented using a queue?
Experiment-4
Aim:- Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node

should point to head and the data value should be replaced with a given value. Return a reference to the new head of

the list. The head pointer given may be null meaning that the initial list is empty.

Function Description

Complete the function insertNodeAtHead in the editor below.

insertNodeAtHead has the following parameter(s):

 SinglyLinkedListNode llist: a reference to the head of a list

 data: the value to insert in the data field of the new node
Input Format

The first line contains an integer n, the number of elements to be inserted at the head of the list.

The next n lines contain an integer each, the elements to be inserted, one per function call.

Constraints

 1<=n<=1000

 1<=list[i]<=1000

Sample Input

5
383
484
392
975
321
Code:-
import java.util.Scanner;

// Definition for singly-linked list node


class SinglyLinkedListNode {
int data;
SinglyLinkedListNode next;

SinglyLinkedListNode(int node_data) {
this.data = node_data;
this.next = null;
}
}

public class InsertNodeAtHead {


// Function to insert a node at the head of the linked list
static SinglyLinkedListNode insertNodeAtHead(SinglyLinkedListNode llist, int data)
{
SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);

if (llist == null) {
// If the list is empty, the new node becomes the head
return newNode;
} else {
// Inserting the new node before the current head
newNode.next = llist;
return newNode;
}
}

// Function to print the linked list


static void printLinkedList(SinglyLinkedListNode head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements to be inserted at the head: ");


int n = scanner.nextInt();

SinglyLinkedListNode head = null;


for (int i = 0; i < n; i++) {
System.out.print("Enter the element to be inserted: ");
int data = scanner.nextInt();
head = insertNodeAtHead(head, data);
}

System.out.print("Linked List after insertion: ");


printLinkedList(head);
}
}
Input:-

Output:-

Viva-Voce Questions
Q.1 What is Linked List?
Q.2 What is the difference between an array and a linked list?
Q.3 What is a Node in a Linked List?
Q.4 What is a Singly Linked List?
Q.5 How do you insert a node at the beginning of a linked list?
Experiment-5
Aim: Given an undirected weighted connected graph, find the Really Special SubTree in it. The Really Special

SubTree is defined as a subgraph consisting of all the nodes in the graph and:

 There is only one exclusive path from a node to every other node.

 The subgraph is of minimum overall weight (sum of all edges) among all such subgraphs.

 No cycles are formed

To create the Really Special SubTree, always pick the edge with smallest weight. Determine if including it will create a

cycle. If so, ignore the edge. If there are edges of equal weight available:

 Choose the edge that minimizes the sum u+v+wt where u and v are vertices and wt is the edge weight.

 If there is still a collision, choose any of them.

Print the overall weight of the tree formed using the rules.

For example, given the following edges:

u v wt
1 2 2
2 3 3
3 1 5
First choose 1->2 at weight 2. Next choose 2->3 at weight 3. All nodes are connected without cycles for a total weight

of 3+2=5 .
Function Description

Complete the kruskals function in the editor below. It should return an integer that represents the total weight of the

subtree formed.

kruskals has the following parameters:

 g_nodes: an integer that represents the number of nodes in the tree

 g_from: an array of integers that represent beginning edge node numbers

 g_to: an array of integers that represent ending edge node numbers

 g_weight: an array of integers that represent the weights of each edge

Input Format

The first line has two space-separated integers g_nodes and g_edges, the number of nodes and edges in the graph.

The next lines each consist of three space-separated integers g_from ,g_to and g_weight, where g_ from

and g_to denote the two nodes between which the undirected edge exists and denotes the weight of that edge.

Constraints

 2<=g_nodes<=3000

 1<=g_edges<=N*(N-1)/2

 1<=g_from,g_to<=N

 0<=g_weight<=10^5

**Note: ** If there are edges between the same pair of nodes with different weights, they are to be considered as is,

like multiple edges.

Output Format

Print a single integer denoting the total weight of the Really Special SubTree.

Sample Input 1
Undirected Weighed Graph:

46
125
133
416
247
324
345
Sample Output 1

12
Explanation 1

Applying Kruskal's algorithm, all of the edges are sorted in ascending order of weight.

After sorting, the edge choices are available as :


1-> 3(w=3), 2->3(w=4),1->2(w=4),3->4(w=5),1->4(w=6) and 2->4(w=7)

Select 1->3(w=3)becauseithasthelowestweightwithoutcreatingacycleSelect 2\rightarrow 3 (w=4)$ because it has the

lowest weight without creating a cycle

The edge 1->2(w=4) would form a cycle, so it is ignored

Select 3->4(w=5) to finish the MST yielding a total weight of 3+4+5=12

Code:-

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Structure to represent an edge in the graph

struct Edge {

int from, to, weight;

Edge(int f, int t, int w) : from(f), to(t), weight(w) {}

};
// Structure to represent a disjoint set

struct DisjointSet {

vector<int> parent, rank;

DisjointSet(int n) {

parent.resize(n + 1);

rank.resize(n + 1);

for (int i = 0; i <= n; i++) {

parent[i] = i;

rank[i] = 0;

int find(int u) {

if (parent[u] != u) {

parent[u] = find(parent[u]);

return parent[u];

}
void unionSets(int u, int v) {

int rootU = find(u);

int rootV = find(v);

if (rank[rootU] < rank[rootV]) {

parent[rootU] = rootV;

} else if (rank[rootU] > rank[rootV]) {

parent[rootV] = rootU;

} else {

parent[rootU] = rootV;

rank[rootV]++;

};

// Function to find the minimum spanning tree weight using Kruskal's algorithm

int kruskals(int g_nodes, vector<int> g_from, vector<int> g_to, vector<int> g_weight) {

int g_edges = g_from.size();

// Create a vector to store the edges

vector<Edge> edges;
for (int i = 0; i < g_edges; i++) {

edges.push_back(Edge(g_from[i], g_to[i], g_weight[i]));

// Sort the edges based on weight

sort(edges.begin(), edges.end(), [](const Edge &a, const Edge &b) {

return a.weight < b.weight;

});

// Create a disjoint set to keep track of connected components

DisjointSet ds(g_nodes);

int totalWeight = 0;

// Iterate through sorted edges and include them in the MST if they don't form a cycle

for (const Edge &edge : edges) {

int rootFrom = ds.find(edge.from);

int rootTo = ds.find(edge.to);

if (rootFrom != rootTo) {

ds.unionSets(rootFrom, rootTo);
totalWeight += edge.weight;

return totalWeight;

int main() {

int g_nodes, g_edges;

cout << "Enter the number of nodes and edges: ";

cin >> g_nodes >> g_edges;

vector<int> g_from(g_edges), g_to(g_edges), g_weight(g_edges);

cout << "Enter the edges (from to weight):" << endl;

for (int i = 0; i < g_edges; i++) {

cin >> g_from[i] >> g_to[i] >> g_weight[i];

int result = kruskals(g_nodes, g_from, g_to, g_weight);


cout << "Total weight of the minimum spanning tree: " << result << endl;

return 0;

Input:-

Output:-

Viva-Voce Questions
Q.1 What is the Purpose of a Minimum Spanning Tree?
Q.2 Define Minimum Spanning Tree (MST)
Q.3 What is a Spanning Tree?
Q.4 Explain Kruskal's Algorithm for Finding the Minimum Spanning Tree.
Q.5 What is a Binary Search Tree (BST)?
Experiment-6
Aim:- Complete the preOrder function in the editor below, which has 1 parameter: a pointer to the root of a binary

tree. It must print the values in the tree's preorder traversal as a single line of space-separated values.

Input Format

Our test code passes the root node of a binary tree to the preOrder function.

Constraints

1<=Nodes in the tree<=500

Output Format

Print the tree's preorder traversal as a single line of space-separated values.

Sample Input

1
\
2
\
5
/ \
3 6
\
4
Sample Output

125346
Explanation

The preorder traversal of the binary tree is printed.

Code:-

#include <iostream>

#include <queue>

using namespace std;

// Definition for a binary tree node.

struct Node {

int data;

Node* left;

Node* right;

Node(int val) : data(val), left(nullptr), right(nullptr) {}

};
// Function to perform preorder traversal of a binary tree

void preOrder(Node* root) {

if (root == nullptr) {

return;

cout << root->data << " ";

preOrder(root->left);

preOrder(root->right);

int main() {

// Constructing the sample binary tree

Node* root = new Node(1);

root->right = new Node(2);

root->right->right = new Node(5);

root->right->right->left = new Node(3);

root->right->right->left->right = new Node(4);

root->right->right->right = new Node(6);


cout << "Preorder Traversal: ";

preOrder(root);

return 0;

Output:-

Viva-Voce Questions
Q.1 What is a Tree in Data Structures??
Q.2 How do you perform an Inorder Traversal of a Binary Tree?
Q.3 What is a Binary Tree?
Q.4 What is the Height of a Tree?
Q.5 What is the Difference Between a Binary Tree and a Binary Search Tree (BST)?
Experiment-7
Aim:- There is a string, s, of lowercase English letters that is repeated infinitely many times. Given an integer,n , find

and print the number of letter a's in the first n letters of the infinite string.

Example

s=’abccac’

n=10

The substring we consider is abcacabcac, the first 10 characters of the infinite string. There are 4 occurrences of a in the

substring.

Function Description

Complete the repeatedString function in the editor below.

repeatedString has the following parameter(s):

 s: a string to repeat

 n: the number of characters to consider

Returns

 int: the frequency of a in the substring

Input Format

The first line contains a single string, .

The second line contains an integer, .

Sample Input 1

aba
10
Code:-
#include <iostream>

using namespace std;

long repeatedString(string s, long n) {


// Count the number of 'a' in the given string s
long count_a_in_s = 0;
for (char ch : s) {
if (ch == 'a') {
count_a_in_s++;
}
}

// Calculate the number of times the string s repeats completely in the first n characters
long complete_repeats = n / s.length();

// Calculate the remaining characters after complete repeats


long remaining_chars = n % s.length();

// Count the number of 'a' in the remaining characters


long count_a_in_remaining = 0;
for (int i = 0; i < remaining_chars; i++) {
if (s[i] == 'a') {
count_a_in_remaining++;
}
}

// Calculate the total count of 'a' in the first n characters


long total_count_a = (complete_repeats * count_a_in_s) + count_a_in_remaining;

return total_count_a;
}

int main() {
// Input values
string s = "aba";
long n = 10;
// Call the repeatedString function
long result = repeatedString(s, n);

// Output the result


cout << "Frequency of 'a' in the substring: " << result << endl;

return 0;
}
Output:-

Viva-Voce Questions
Q.1 What is a string?
Q.2 How are strings represented in memory?
Q.3 How do you find the length of a string?
Q.4 How do you reverse a string?
Q.5 How do you compare two strings for equality?
Experiment-8
Aim:- Given an array of integers and a target sum, determine the sum nearest to but not exceeding the target that can be

created. To create the sum, use any element of your array zero or more times.

For example, if arr=[2,3,4] and your target sum is 10 , you might select [2,2,2,2,2],[2,2,3,3] or [3,3,3,1] . In this case,

you can arrive at exactly the target.

Function Description

Complete the unboundedKnapsack function in the editor below. It must return an integer that represents the sum

nearest to without exceeding the target value.

unboundedKnapsack has the following parameter(s):

 k: an integer

 arr: an array of integers

Input Format

The first line contains an integer t , the number of test cases.

Each of the next t pairs of lines are as follows:

- The first line contains two integers n and k, the length of arr and the target sum.

- The second line contains n space separated integers arr[i] .

Output Format

Print the maximum sum for each test case which is as near as possible, but not exceeding, to the target sum on a

separate line.
Sample Input

2
3 12
169
59
34448

Code:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int unboundedKnapsack(int k, vector<int>& arr) {


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

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


for (int j = 0; j < arr.size(); j++) {
if (arr[j] <= i) {
dp[i] = max(dp[i], dp[i - arr[j]] + arr[j]);
}
}
}

return dp[k];
}

int main() {
// Input values
int t;
cin >> t;

while (t--) {
int n, k;
cin >> n >> k;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Call the unboundedKnapsack function


int result = unboundedKnapsack(k, arr);

// Output the result


cout << "Maximum sum: " << result << endl;
}

return 0;
}
Output:

Viva-Voce Questions
Q.1 What are the different variations of the Knapsack Problem?
Q.2 What is dynamic programming approach?
Q.3 Explain the Unbounded Knapsack Problem.
Q.4 What is the Subset Sum Problem?
Q.5 How can the Subset Sum Problem be related to the Knapsack Problem?
Experiment-9
Aim:- To implement traveling salesman problem using naive approach.
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

// Function to calculate the total cost of a tour


int calculateCost(vector<vector<int>>& graph, vector<int>& tour) {
int cost = 0;
int n = graph.size();

for (int i = 0; i < n - 1; i++) {


cost += graph[tour[i]][tour[i + 1]];
}

// Add the cost of returning to the starting city


cost += graph[tour[n - 1]][tour[0]];

return cost;
}

// Function to find the minimum cost using naive approach


int travelingSalesmanNaive(vector<vector<int>>& graph, int start) {
int n = graph.size();
vector<int> tour(n);
for (int i = 0; i < n; i++) {
tour[i] = i;
}

int minCost = INT_MAX;


do {
// Check if the current tour is a valid tour
if (tour[0] == start) {
int currentCost = calculateCost(graph, tour);
minCost = min(minCost, currentCost);
}
} while (next_permutation(tour.begin(), tour.end()));

return minCost;
}

int main() {
// Define the graph as an adjacency matrix
vector<vector<int>> graph = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

int startCity = 0; // Starting city index

// Call the travelingSalesmanNaive function


int minCost = travelingSalesmanNaive(graph, startCity);

// Output the result


cout << "Minimum cost of the tour: " << minCost << endl;

return 0;
}

Output:
Viva-Voce Questions
Q.1 What is Traveling Salesman Problem?
Q.2 Explain the dynamic programming approach to solving TSP.
Q.3 What are the steps involved in the nearest neighbor approach?
Q.4 What is the connection between TSP and the MST?
Q.5 Discuss the branch and bound technique for solving TSP.
Experiment-10
Aim:-Given a set of non-negative integers and a value sum, the task is to check if there is a subset
of the given set whose sum is equal to the given sum.
Examples:
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True
Explanation: There is a subset (4, 5) with sum 9.
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30
Output: False
Explanation: There is no subset that add up to 3

Code:
#include <iostream>
#include <vector>

using namespace std;

// Function to check if there exists a subset with the given sum


bool isSubsetSum(vector<int>& set, int sum) {
int n = set.size();
vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1, false));

// If sum is 0, then answer is true


for (int i = 0; i <= n; i++)
dp[i][0] = true;

// Fill the dp table


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
// If the current element is greater than the sum, skip it
if (set[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - set[i - 1]];
}
}

return dp[n][sum];
}

int main() {
vector<int> set = {3, 34, 4, 12, 5, 2};
int sum1 = 9;
int sum2 = 30;

// Check if there is a subset with sum = 9


if (isSubsetSum(set, sum1))
cout << "Subset with sum " << sum1 << " exists.\n";
else
cout << "Subset with sum " << sum1 << " does not exist.\n";

// Check if there is a subset with sum = 30


if (isSubsetSum(set, sum2))
cout << "Subset with sum " << sum2 << " exists.\n";
else
cout << "Subset with sum " << sum2 << " does not exist.\n";

return 0;
}
Output:

Viva-Voce Questions
Q.1 What is a subset?
Q.2 How would you define the concept of a power set?
Q.3 Can an empty set be considered a subset?
Q.4 What approaches can be used to solve the subset sum problem?
Q.5 Explain the concept of the intersection of two sets.

You might also like