Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

LAB MANUAL

Analysis and Design of Algorithms

Course Code : CSE303

Programme Name: B.Tech(CSE/IT)-V Sem

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Amity School of Engineering & Technology


Amity University Uttar Pradesh

1
Contents Page No
1. Preamble 3
a. Introduction
b. Remote mode of teaching and learning
c. Challenges
d. Use of virtual labs for teaching and learning
e. Advantages
f. Resources
g. Standard plan for conduct of virtual labs
2. How to use the manual 6
3. Tabulation of labs/resources 6
a. Subject area
b. Brief about the lab / resource
c. Hyperlink to the resource
4. Discipline / area-wise virtual labs manual of relevant courses 7
5. List of coordinators and resource persons for Virtual Labs 54

2
1 Preamble
a. Introduction:
Virtual labs are used in teaching and learning with the following objectives

a. To enthuse students to conduct experiments by arousing their curiosity.

b. To provide remote access to Labs in various disciplines of Science and


Engineering.

b. Remote mode of teaching and learning:


Physical distances and the lack of resources make us unable to perform experiments,
especially when they involve sophisticated instruments. Also, good teachers are always a
scarce resource. Web-based and video-based courses address the issue of teaching to
some extent. Conducting joint experiments by two participating institutions and sharing
costly resources has always been a challenge. With the present-day internet and computer
technologies the above limitations can no more hamper students and researchers in
enhancing their skills and knowledge. Also, in a country such as ours, costly instruments
and equipment need to be shared with fellow researchers to the extent possible. Web
enabled experiments can be designed for remote operation and viewing to enthuse the
curiosity and innovation into students. This would help in learning basic and advanced
concepts through remote experimentation. Today most equipment has a computer
interface for control and data storage. It is possible to design good experiments around
some of this equipment which would enhance the learning of a student. Internet-based
experimentation further permits use of resources, knowledge, software, and data available
on the web, apart from encouraging skilful experiments being simultaneously performed
at points separated in space (and possibly, time).

3
c. Challenges
Traditionally, hands-on software training was provided using physical labs. Learners would
congregate in classrooms filled with expensive computers pre-loaded with the necessary lab
material. Instructors with limited tracking ability did their best to guide attendees through
complicated material, despite significant limitations.
However, in an age where learners demand access to training at the touch of a button, the cons of
in-person labs outweigh the pros. And now the global pandemic has made in-person training
unsafe, requiring organizations to find alternatives to in-person, instructor led labs for their
software training.

Here are some of the key limitations to the way traditional software labs were delivered:

• Post-pandemic safety: For better or worse, Covid-19 has changed the way we deliver
training of all kinds. In-person, instructor-led software labs are no longer safe given what
we know about disease transmission in tight spaces and during travel.

• Cumbersome Set-up logistics: For these labs, machines would have to be set up in a
classroom environment prior to the training date, requiring extensive planning and
logistics.

• Excessive Set-up costs: Machines would often have to be shipped to training locations
and instructors flown to the physical space.

• Endless Machine Maintenance: For these labs to be effective, the machines used would
have to be maintained constantly, updated with the software necessary for training
exercises. And that’s before we even mention troubleshooting.

• Limited Scale: Because there were limited available spaces at the physical location,
training could not be scaled effectively.

4
• Rigid Schedule: Attendees would find it hard to keep up with day-to-day demands of
their job to immerse themselves in an on-site training.

• Lack of Instructor Oversight: because individuals would often be responsible for their
own machines on-site, instructors would have limited oversight during the training

• Lack of practicality: Simulations are better than nothing, but they lack the impact of
real-world, hands-on training in a live environment.

d. Use of virtual labs for teaching and learning


Virtual Labs will provide to the students the result of an experiment by one of the following
methods (or possibly a combination)
• Modeling the physical phenomenon by a set of equations and carrying out simulations to
yield the result of the experiment. This can, at-the-best, provide an approximate version
of the ‘real-world’ experiment.
• Providing measured data for virtual lab experiments corresponding to the data previously
obtained by measurements on an actual system.
• Remotely triggering an experiment in an actual lab and providing the student the result of
the experiment through the computer interface. This would entail carrying out the actual
lab experiment remotely.
• Virtual Labs will be made more effective and realistic by providing additional inputs to
the students like accompanying audio and video streaming of an actual lab experiment
and equipment.

e. Advantages:
Following are the advantages of using virtual labs
• Enhances students' enthusiasm for learning through interactivity
• To provide remote access to Labs in various disciplines of Engineering to cater to
students at UG and PG level
• Simplifying complex procedures so that more complicated workshops can be conducted

5
• Offering a safe workshop environment, and enabling a convenient platform for student
assessments
• Improving time efficiency
• Maximizing time and space flexibilities

f. Resources
Amity University has its own Amity V Lab for teaching and learning of course Analysis and
Design of Algorithms [CSE303]. Students are able to access C/C++ compiler using the URL
http://202.12.103.135/vlab/interface/ide.html free of cost through this portal, in order to perform
Lab Experiments.

g. Standard plan for conduct of virtual labs


Students will use resources which are available at Amity V Lab. Through this portal student will
be able to conduct all labs using C/C++ compiler.

2. How to use the manual

This lab manual will be used for Analysis and Design of Algorithm [CSE303]. This will also
guide the students about the tasks to be performed in each experiment.

3. Tabulation of labs/resources
a. Subject area : Computer Science & Engineering
b. Brief about the lab/resource: The goal of this lab is to make students aware of
various techniques used to evaluate the efficiency of a particular algorithm.
Students eventually should learn to design efficient algorithm for a particular
program.
c. Hyperlink to the resource
http://202.12.103.135/vlab/interface/ide.html

This link will be functional once student is enrolled to the course.

6
4. Course Title: Analysis and Design of Algorithm
Course Code : CSE303 Credit Unit : 05
Learning Outcomes:

Students will be able to:


• Apply knowledge of mathematics, science, engineering and computing appropriate to the
discipline.
• Analyse a problem and identify and define the computing requirements appropriate to its
solution.
• Understand and analyse the recursive and non-recursive algorithms.
• Design, implement, and evaluate a computer-based system, process, component, or
programmer to meet desired needs.
• Use current techniques, skills, and tools necessary for computing practice.

List of Practical:

S. No Programs Page No
Introduction to Virtual tool 10
1 Implementation of various sorting techniques: Bubble, Selection & Insertion 12
and their comparison
2 Implement Recursive Binary search and determine the time taken to search an 16
element. Repeat the experiment for different values of n, the number of
elements in the list to be searched and plot a graph of the time taken versus n.
3 Sort a given set of elements using Quick sort method and determine the time 19
taken to sort the elements. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken
versus n.
4 Strassen matrix multiplication 22
5 From a given vertex in a weighted connected graph, find shortest paths to 24
other vertices using Dijkstra's algorithm.
6 Implement Traveling Salesman problem using dynamic programming 26
7 0/1 Knapsack problem using Dynamic Programming 29
8 From a given starting node in a digraph, print all the nodes reachable by using 31
DFS method.
9 Consider the problem of N queen on an (NxN) chessboard. Two queens are 34
said to attack each other if they are on the same row, column, or diagonal.
Implements backtracking algorithm to solve the problem i.e. place N non-
attacking queens on the board.
10 Implement Knapsack Problem based on Backtracking algorithm. 37

7
11 Implement Traveling Salesman problem based on Branch and Bound 40
technique.
Open Ended Experiments
A university department is shifting its department library to a more spacious 44
room on a newly constructed floor. The books from the library have been
packed into m cartons, numbered 1, 2, …, m, containing b1, b2, …, bm books,
respectively, and transported to the new library room.
There are k student volunteers available to unpack the m cartons, where k ≤ m.
Each carton must be assigned to a single volunteer, and every volunteer must
get a non-empty continuous sequence of cartons to unpack.
1
More formally, we need to find numbers 0 = c0 < c1 < c2 < … <ck = m such
that volunteer j, 1 ≤ j ≤ k unpacks cartons cj-1+1 to cj.
The time each volunteer takes to unpack a carton is directly proportional to the
number of books in the carton. The goal is parallelize the unpacking to finish
in the fastest possible time. For this, we need to assign cartons such that the
maximum number of books assigned to any one volunteer is minimized.
Suppose we are given Indian currency notes of all denominations, e.g. 46
{1,2,5,10,20,50,100,500,1000}. The problem is to find the minimum number
of currency notes to make the required amount A, for payment. Further, it is
assumed that currency notes of each denomination are available in sufficient
numbers, so that one may choose as many notes of the same denomination as
are required for the purpose of using the minimum number of notes to make
2 the amount A;
Intuitively, to begin with, we pick up a note of denomination D, satisfying the
conditions.
i) D ≤ 289 and
ii) if D1 is another denomination of a note such that D1 ≤ 289, then D1 ≤ D.
Develop a Hamiltonian Path in an undirected graph is a path that visits each 48
vertex e xactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a
Hamiltonian Path such that there is an edge (in graph) from the last vertex to
3 the first vertex of the Hamiltonian Path. Develop a program to implement the
solution of Travelling Salesman Problem by considering the Hamiltonian
cycle approach.
Given two sequences, a subsequence is a sequence that appears in the same 49
relative order, but not necessarily contiguous. For example, “abc”, “abg”,
“bdf”, “aeg”, „”acefg”, .. etc are subsequences of “abcdefg”. So a string of
4 length n has 2^n different possible subsequences. It is a classic computer
science problem, the basis of file comparison programs and has applications in
bioinformatics. Develop a program to implement the solution of Longest
Common Sub-sequence problem
The exit polls indicate that the sitting MLA is likely to lose the upcoming 50
election. The party high command instructs him to undertake a padayatra
through his constituency to boost his popularity. To maximize coverage of the
constituency, the party decides that he should choose a circular route that

8
5 returns to the starting point without using any road twice. The route need not
visit all the towns and villages in the constituency.
Being averse to physical exercise, the MLA would like to minimize the
distance that he has to walk. He has a helicopter at his disposal, so he can
begin the padayatra at any town or village.
The task is to help him find the shortest circular route. You are guaranteed that
there is always at least one circular route.
The kingdom is falling into ruin. People live in fear. Dragons pillage, kill, and 52
just generally cause as much havoc as they possibly can. The king has just
sent out a royal decree:
6 To any man out there who is able to bring me the heads of K dragons, I shall
bequeath a lordship–to him, his sons and his grandsons, till the end of time.
Having seen this royal decree and knowing that you are capable of killing
dragons thanks to your extensive medieval combat training, you set out on a
quest to hunt down the evil creatures. Being a busy kind of guy, you would
like to complete your quest quickly and kill K dragons through the shortest
route.
The kingdom is arranged in a grid with R rows, numbered 0 to R-1, and C
columns, numbered 0 to C-1 You start your quest at the top left corner of the
grid, (0,0).
The total number of dragons in the kingdom is D, of which you have to kill K.
Dragons are very territorial in nature, so each row of the grid contains at most
one dragon. Also, since the kingdom is situated on a hill, you travel only
downwards on the grid, though you may move left or right as you please.

Lab/ Practical/ Studio Assessment:

Continuous Assessment/Internal Assessment 40% End Term


Examination 60%
Components Performance Lab Record Viva Attendance Practical viva
(Drop down)
Weightage (%) 15 10 10 5 30 30

9
Introduction to Virtual Tool
To familiarize with virtual tool, student must follow the given steps:
Step 1: Open the browser.
Step 2: Type the following link : http://202.12.103.135/vlab/interface/ide.html
Once you type and press enter, following page will open.

Step 3: After following page open for you, next step is to select appropriate compiler
C/C++ of his/her choice from top left window.

10
Step 4: Now, Virtual Compiler is ready . Student can type the code in left window (as
shown in screen shot) and output will be visible in bottom -right window by clicking
the run button on the top.

11
Program-1
OBJECTIVE: Implementation of various sorting techniques: Bubble, Selection &
Insertion, and their comparison.

RESOURCES:

Amity Online C/C++ COMPILER (URL)

http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:

Bubble sort repeatedly compares and swaps(if needed) adjacent elements in every pass. In i-th
pass of Bubble Sort (ascending order), last (i-1) elements are already sorted, and i-th largest
element is placed at (N-i)-th position, i.e. i-th last position.

Optimized version of Bubble sort Algorithm: Check if there happened any swapping
operation in the inner loop (pass execution loop) or not. If there is no swapping in any pass, it
means the array is now fully sorted, hence no need to continue, stop the sorting operation. So
we can optimize the number of passes when the array gets sorted before the completion of all
passes. And it can also detect if the given / input array is sorted or not, in the first pass.

Selection sort selects i-th smallest element and places at i-th position. This algorithm divides
the array into two parts: sorted (left) and unsorted (right) subarray. It selects the smallest
element from unsorted subarray and places in the first position of that subarray (ascending
order). It repeatedly selects the next smallest element.

Insertion Sort is a simple comparison-based sorting algorithm. It inserts every array element
into its proper position. In i-th iteration, previous (i-1) elements (i.e., subarray Arr[1:(i-1)]) are
already sorted, and the i-th element (Arr[i]) is inserted into its proper place in the previously
sorted subarray.

12
PSEUDOCODE:

Bubble Sort:
BubbleSort (Arr, N) // Arr is an array of size N.
{
For (I:=1 to (N-1) ) // N elements =>(N-1) pass
{
//Swap adjacent elements of Arr[1:(N-I)]such that largest
//among { Arr[1], Arr[2], ...,Arr[N-I] } reaches to Arr[N-I]
noSwap = true;// Check occurrence of swapping in inner loop
For ( J:= 1 to (N-I)) // Execute the pass
{
If (Arr[J] > Arr[J+1])
{
Swap(Arr[j], Arr[J+1]);
noSwap = false;
}
}
If (noSwap) // exit the loop
break;
}
}

Selection Sort:

SelectionSort(Arr, N) // Arr is an array of size N.


{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// I=N is ignored, Arr[N] is already at proper place. Arr[1:(I-1)]
// is sorted subarray, Arr[I:N]is undorted subarray smallest among
//{ Arr[I], Arr[I+1], Arr[I+2], ..., Arr[N] } is at place min_index
min_index = I;
For ( J:= I+1 to N ) // Search Unsorted Subarray (Right lalf)
{
If (Arr[J]<Arr[min_index])
min_index = J; // Current minimum
}

13
// Swap I-th smallest element with current I-th place element
If (min_Index != I)
Swap ( Arr[I], Arr[min_index] );
}
}

Insertion Sort:

InsertionSort(Arr,N) // Arr is an array of size N.


{
For ( I:= 2 to N ) // N elements => (N-1) pass
{
// Pass 1 is trivially sorted, hence not considered
// Subarray { Arr[1], Arr[2], ..., Arr[I-I] } is already sorted
insert_at = I;
// Find suitable position insert_at, for Arr[I]
// Move subarray Arr [ insert_at: I-1 ] to one position right
item = Arr[I];
J=I-1;
While ( J ? 1 && item < Arr[J] )
{
Arr[J+1] = Arr[J]; // Move to right
// insert_at = J;
J--;
}
insert_at = J+1; // Insert at proper position
Arr[insert_at] = item; // Arr[J+1] = item;
}
}
}

PROCEDURE:

1. Open virtual C/C++ compiler using the URL


http://202.12.103.135/vlab/interface/ide.html, write a program, after that, save the
program with .c extension.
2. Compile/run the program using the run button

14
EXPECTED OUTPUT:

For Example: Running Insertion sort, Output must be shown after each iteration (Pass) as
follows:

Repeat the experiment for different values of n, the number of elements in the array and plot a
graph of the time taken versus n.
One graph should also be plotted for already sorted input array for all the three algorithms.
For Example: Graph for comparison of O(n2) sorting algorithm is shown below:

Note: The graph does seem to show that the algorithms are quadratic in growth, where
insertion sort is the marginally the most efficient followed by selection sort, and then bubble
sort.

15
Program-2
OBJECTIVE:

Implement Recursive Binary search and linear search and determine the time taken to search
an element. Repeat the experiment for different values of n, the number of elements in the list
to be searched and plot a graph of the time taken versus n.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
A linear search scans one item at a time, without jumping to any item .
1. The worst-case complexity is O(n), sometimes known an O(n) search
2. Time taken to search elements keep increasing as the number of elements are
increased.
A binary search however, cut down your search to half as soon as you find middle of a sorted
list.
1. The middle element is looked to check if it is greater than or less than the value to
be searched.
2. Accordingly, search is done to either half of the given list

PSEUDOCODE:

// A recursive binary search function returns location of x in given


array //arr[l..r], if x is present in the array,otherwise -1.

int binarySearch(int arr[], int l, int r, int x)


{
if (r >= l) {
int mid = l + (r - l) / 2;

// If the element is present at the middle


// itself
if (arr[mid] == x)
return mid;

16
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);

// Else the element can only be present


// in right subarray
return binarySearch(arr, mid + 1, r, x);
}

// We reach here when element is not


// present in array
return -1;
}

EXPECTED OUTPUT:
Case 1

*****MENU*******
1. Binary Search
2. Linear Search
3. Exit

Enter your choice


1

17
Also, repeat the experiment for different values of n, the number of elements in the list to be
searched for Linear and binary search and plot a graph of the time taken versus n. For
example:

18
Program-3
OBJECTIVE:
Sort a given set of elements using Quick sort method and determine the time taken to sort the
elements. Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n.
RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
Quicksort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given array around the picked pivot. There are many different versions of quickSort that pick
pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
The key process in quicksort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All th is
should be done in linear time.
PSEUDOCODE:

QUICKSORT (A, p, r)
{
If (p < r) /* Base Condition
{
q← PARTITION (A, p, r) //Divide Step
QUICKSORT (A, p, q-1) // Conquer
QUICKSORT (A, q+1, r) // Conquer
}
}

PARTITION (A, p, r)
{

19
1: x ← A[r] //select last element
2: i ← p – 1 //I is pointing one position before than p
3: for j ← p to r − 1 do
{
4: if (A[j] ≤ r)
{
5: i ← i + 1
6: Exchange (A[i] ↔ A[j])
}
} //end for loop
7: Exchange (A [i + 1] and A[r])
8: return ( i+ 1)
} //End of Algorithm

EXPECTED OUTPUT:

Output array should be displayed after each iteration of for loop (line no 3 of PARTITION())
Also Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n.

20
21
Program-4
OBJECTIVE:
Implement V. Strassen matrix multiplication.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:

Consider the problem of computing matrix multiplication C = A · B, where the (i, j)th output
element is computed by the classical formula Cij = kAik · Bkj. One "naive" ordering of the
computation of the classical algorithm can be specified simply by three nested loops. The
running time of this naïve approach required O(n3) time.
Strassen's key idea is to multiply 2 × 2 matrices using seven scalar multiplies instead of eight.
Because n × n matrices can be divided into quadrants, Strassen's idea applies recursively. Each of
the seven quadrant multiplications is computed recursively, and the computational cost of
additions and subtractions of quadrants is (n2). Thus, the recurrence for the flop count is
F(n) = 7F (n/2) + (n2) with base case F(1) = 1, which yields F(n)=( ), which is
asymptotically less computation than the classical algorithm.

PSEUDOCODE:

22
EXPECTED OUTPUT:

Perform matrix multiplication by normal method or divide and conquer and using Strassen
method. Compute the variation between the running time of both algorithms and display the
same using graphs.

23
Program-5
OBJECTIVE:

From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm.

RESOURCES:

Amity Online C/C++ COMPILER (URL)


http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:

1) Create a set S that keeps track of vertices included in shortest path tree, i.e., whose
minimum distance from source is calculated and finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertexso that it is
picked first.
3) While S doesn’t include all vertices
a) Pick a vertex u which is not there in S and has minimum distance
value.
b) Include u to S.
c) Update distance value of all adjacent vertices of u.

To update the distance values, iterate through all adjacent vertices. For every adjacent vertex
v, if sum of distance value of u (from source) and weight of edge u-v, is less than the
distance value of v, then update the distance value of v.

PSEUDOCODE:

A min-priority queue is an abstract data type that provides 3 basic operations :


add_with_priority(), decrease_priority() and extract_min(). As mentioned earlier, using such a
data structure can lead to faster computing times than using a basic queue

24
1 function Dijkstra(Graph, source):
2 dist[source] ← 0 // Initialization
3
4 create vertex priority queue Q
5
6 for each vertex v in Graph:
7 if v ≠ source
8 dist[v] ← INFINITY // Unknown distance from
source to v
9 prev[v] ← UNDEFINED // Predecessor of v
10
11 Q.add_with_priority(v, dist[v])
12
13
14 while Q is not empty: // The main loop
15 u ← Q.extract_min() // Remove and return
best vertex
16 for each neighbor v of u: // only v that are still
in Q
17 alt ← dist[u] + length(u, v)
18 if alt < dist[v]
19 dist[v] ← alt
20 prev[v] ← u
21 Q.decrease_priority(v, alt)
22
23 return dist, prev

EXPECTED OUTPUT:

Enter the number of vertices V(G) = 5


Enter the cost of the edges (Enter 999 if the edge is not present or for the self-loop):

25
Program 6
OBJECTIVE:

Implement Traveling Salesman problem using dynamic programming

RESOURCES:

Amity Online C/C++ COMPILER (URL)


http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:

TSP using Dynamic Programming:


Let the given set of vertices be {1, 2, 3, 4,….n}. Let us consider 1 as starting and ending point
of output. For every other vertex i (other than 1), we find the minimum cost path with 1 as the
starting point, i as the ending point and all vertices appearing exactly once. Let the cost of this
path be cost(i), the cost of corresponding Cycle would be cost(i) + dist(i, 1) where dist(i, 1) is
the distance from i to 1. Finally, we return the minimum of all [cost(i) + dist(i, 1)] values. This
looks simple so far. Now the question is how to get cost(i)?
To calculate cost(i) using Dynamic Programming, we need to have some recursive relation in
terms of sub-problems. Let us define a term C(S, i) be the cost of the minimum cost path
visiting each vertex in set S exactly once, starting at 1 and ending at i.
We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset,
then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present in
every subset.
If size of S is 2, then S must be {1,i},
C(S,i) = dist(1,i)
Else if size of S is greater than 2.
C(S,i) = min {C(S-{i},j) + dis(j,i)} where j belongs to S,
j != i and j != 1.

For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have nth
in them.
Using the above recurrence relation, we can write dynamic programming-based solution. There
are at most O(n*2n) subproblems, and each one takes linear time to solve. The total running

26
time is therefore O(n 2*2n). The time complexity is much less than O(n!), but still exponential.
Space required is also exponential. So this approach is also infeasible even for slightly higher
number of vertices.

PSEUDOCODE:

In this algorithm, we take a subset N of the required cities needs to be visited, distance among
the cities dist and starting city s as inputs. Each city is identified by unique city id like {1,2,3,
…., n}.

Initially, all cities are unvisited, and the visit starts from the city s . We assume that the initial
travelling cost is equal to 0. Next, the TSP distance value is calculated based on a recursive
function. If the number of cities in the subset is two, then the recursive function returns their
distance as a base case.

27
On the other hand, if the number of cities is greater than 2, then we’ll calculate the distance from
the current city to the nearest city, and the minimum distance among the remaining cities is
calculated recursively.

Finally, the algorithm returns the minimum distance as a TSP solution.

Here we use a dynamic approach to calculate the cost function Cost(). Using recursive calls,
we calculate the cost function for each subset of the original problem.

In the dynamic algorithm for TSP, the number of possible subsets can be at most N*2N. Each
subset can be solved in O(N) times. Therefore, the time complexity of this algorithm would
be O(N2*2N).

EXPECTED OUTPUT:

28
Program-7
OBJECTIVE:
0/1 Knapsack problem using Dynamic Programming

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:

Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and
wt[0..n-1] which represent values and weights associated with n items respectively. Also given
an integer W which represents knapsack capacity, find out the maximum value subset of val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an
item, either pick the complete item or don’t pick it (0-1 property).

PSEUDOCODE:

Dynamic-0-1-knapsack (n,W,w1,w2,…wn,v1,v2,…vn)
1.
2.
3.
4.

29
15.

Here, first, the algorithm creates a matrix of size ((N+1)X(W+1)).


Every entry V[i,w] denotes the maximum value the knapsack can take with a particular weight
limit w and i items. We iterate over all possible weights (along the column) up to the weight
limit W and then pick a new item i (next row) to see how the value of the knapsack increases.
To compute the maximum value at any given position in the matrix:For each entry V[i,j]
If wi >j then //exclude the item
V[𝑖,𝑗]=𝑉[𝑖−1, 𝑗]
Else
If wi <=j then // Item included
V[𝑖,𝑗]=max{ 𝑉[𝑖−1,𝑗],[vi+𝑉[𝑖−1,𝑗−wi]]}
The function V[i-1,w] denotes the value at the position right above the current position (i-1,w),
to check without adding the item i, and V[i-1, w-wi]+vi present the value of the knapsack if the
current item is added. Running time of this 0-1Knasack algorithm is O(n.W).
EXPECTED OUTPUT:

30
Program 8
OBJECTIVE:
From a given starting node in a digraph, print all the nodes reachable by using DFS method.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves
exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.
Here, the word backtrack means that when you are moving forward and there are no more nodes
along the current path, you move backwards on the same path to find nodes to traverse. All the
nodes will be visited on the current path till all the unvisited nodes have been traversed after
which the next path will be selected.
This recursive nature of DFS can be implemented using stacks. The basic idea is as follows:
• Pick a starting node and push all its adjacent nodes into a stack.
• Pop a node from stack to select the next node to visit and push all its adjacent nodes into
a stack.
• Repeat this process until the stack is empty. However, ensure that the nodes that are
visited are marked. This will prevent you from visiting the same node more than once. If
you do not mark the nodes that are visited and you visit the same node more than once,
you may end up in an infinite loop.

31
PSEUDOCODE:

DFS-iterative (G, s): //Where G is graph


and s is source vertex
let S be stack
S.push( s ) //Inserting s in stack
mark s as visited.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = S.top( )
S.pop( )
//Push all the neighbours of v in stack that are not visited
for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited

DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)

Complexity Analysis:
• Time complexity: O(V + E), where V is the number of vertices and E is the number

of edges in the graph.


• Space Complexity: O(V).
Since an extra visited array is needed of size V.
EXPECTED OUTPUT:

32
OR
Output may be in the following form:

For Example, consider the following graph:

33
Experiment 9
OBJECTIVE:
Consider the problem of N queen on an (NxN) chessboard. Two queens are said to attack each
other if they are on the same row, column, or diagonal. Implements backtracking algorithm to
solve the problem i.e. place N non-attacking queens on the board.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other. For example, following is a solution for 4 Queen problem.

The expected output is a binary matrix which has 1s for the blocks where queens are placed. For
example, following is the output matrix for above 4 queen solutions.

{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}

1. Start in the leftmost column


2. If all queens are placed
return true
3. Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this then mark this [row, column] as part of the
solution and recursively check if placing queen here leads to a solution.
b) If placing the queen in [row, column] leads to a solution then return true.

34
c) If placing queen does not lead to a solution then unmark this [row, column]
(Backtrack)and go to step (a) to try other rows.
4. If all rows have been tried and nothing worked,
return false to trigger backtracking.

PSEUDOCODE

Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from the leftmost column.
When we place a queen in a column, we check for clashes with already placed queens. In the
current column, if we find a row for which there is no clash, we mark this row and column as
part of the solution. If we do not find such a row due to clashes then we backtrack and return
false.

1) Start in the leftmost column


2) If all queens are placed
return true
3) Try all rows in the current column.
Do following for every tried row.
a) If the queen can be placed safely in this row
then mark this [row, column] as part of the
solution and recursively check if placing
queen here leads to a solution.
b) If placing the queen in [row, column] leads to
a solution then return true.
c) If placing queen doesn't lead to a solution then
unmark this [row, column] (Backtrack) and go to
step (a) to try other rows.
3) If all rows have been tried and nothing worked,
return false to trigger backtracking.

35
EXPECTED OUTPUT:

Enter the number of Queen’s (N) : 4

(The 1 value indicate placements of queens)

Solution #1:
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
Solution #2:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Total Solution for 4 Queen’s problem=2
e.g.

OR

Output may be in form of Tuple as :


[2 4 1 3 ] [3 1 4 2 ]

36
Experiment 10
OBJECTIVE:
Implement Knapsack Problem based on Backtracking algorithm.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
The Backtracking Algorithm for the 0–1 Knapsack Problem is defined as:
Let n items be given, where each item has a weight and a profit. The weights and profits are
positive integers. Furthermore, let a positive integer W be given. Determine a set of items with
maximum total profit, under the constraint that the sum of their weights cannot exceed W.

PSEUDOCODE

Inputs: Positive integers n and W; arrays w and p, each indexed from 1 to n, and each containing
positive integers sorted in nonincreasing order according to the values of p[i]/w[i].
Outputs: an array bestset indexed from 1 to n, where the values of bestset[i] is "yes" if the ith
item is included in the optimal set and is "no" otherwise; an integer maxprofit that is the
maximum profit.

void knapsack (index i, int profit, int weight)


{
if (weight <= W&& profit > maxprofit){ // This set is best
maxprofit = profit; // so far.
numbest = i; // Set numbest to
bestset = include; // number of items
} // considered. Set
// bestset to this
// solution.
if (promising(i)){
include [i + 1] = "yes"; // Include w[i + 1].
knapsack(i + 1, profit + p[i + 1], weight + w[i + 1]);
include [i + 1] = "no"; // Do not include
knapsack (i + 1, profit, weight); // w[i + 1].

37
}
}

bool promising (index i)


{
index j, k;
int totweight;
float bound;

if (weight >= W) // Node is promising only


return false; // if we should expand to
else { // its children. There must
j = i + 1; // be some capacity left
for
bound = profit; // the children.
totweight = weight;
while (j <= n && totweight + w[j] < = W){
// Grab as many items as
totweight = totweight + w[j]; // possible.
bound = bound + p[j];
j++;
}
k = j; // Use k for consistency
if (k <=n) // with formula in text.
bound = bound + (W - totweight) * p[k]/w[k];
// Grab fraction of kth

return bound > maxprofit; // item.


}
}

Following our usual convention, n, w, p, W, maxprofit, include, bestset, and numbest are not
inputs to either routine. If these variables were defined globally, the following code would
produce the maximum profit and a set that has that profit:

numbest = 0;
maxprofit = 0;
knapsack(0, 0, 0);
cout << maxprofit; // Write the maximum
profit.
for (j = 1; j <= numbest; j++) // Show an optimal set of
items.
cout << bestset[i];

38
EXPECTED OUTPUT:
Input :

Output:

39
Experiment 11
OBJECTIVE:
Implement Traveling Salesman problem based on Branch and Bound technique.

RESOURCES:
Amity Online C/C++ COMPILER (URL)
http://202.12.103.135/vlab/interface/ide.html

PROGRAM LOGIC:
Given a set of cities and distance between every pair of cities, the problem is to find the shortest
possible tour that visits every city exactly once and returns to the starting point.

For example, consider the graph shown in figure on right side. A TSP tour in the graph is 0-1-3-
2-0. The cost of the tour is 10+25+30+15 which is 80.

Algorithm:

Branch and Bound Solution


As seen in the previous articles, in Branch and Bound method, for current node in tree, we
compute a bound on best possible solution that we can get if we down this node. If the bound on
best possible solution itself is worse than current best (best computed so far), then we ignore the
subtree rooted with the node.

Note that the cost through a node includes two costs.


1) Cost of reaching the node from the root (When we reach a node, we have this cost computed)

40
2) Cost of reaching an answer from current node to a leaf (We compute a bound on this cost to
decide whether to ignore subtree with this node or not).

In branch and bound, the challenging part is figuring out a way to compute a bound on best
possible solution. Below is an idea used to compute bounds for Traveling salesman problem.

Cost of any tour can be written as below.

Cost of a tour T = (1/2) * ∑ (Sum of cost of two edges adjacent to u and in the tour T)

where u ∈ V

For every vertex u, if we consider two edges through it in T, and sum their costs. The overall
sum for all vertices would be twice of cost of tour T (We have considered every edge twice.)

(Sum of two tour edges adjacent to u) >= (sum of minimum weight two edges adjacent to u)

Cost of any tour >= 1/2) * ∑ (Sum of cost of two minimum weight edges adjacent to u)

where u ∈ V

Now we have an idea about computation of lower bound. Let us see how to how to apply it
state space search tree. We start enumerating all possible nodes (preferably in lexicographical
order)

1. The Root Node: Without loss of generality, we assume we start at vertex “0” for which the
lower bound has been calculated above.

Dealing with Level 2: The next level enumerates all possible vertices we can go to (keeping in
mind that in any path a vertex has to occur only once) which are, 1, 2, 3… n (Note that the
graph is complete). Consider we are calculating for vertex 1, Since we moved from 0 to 1, our
tour has now included the edge 0-1. This allows us to make necessary changes in the lower
bound of the root.

Lower Bound for vertex 1 =

Old lower bound - ((minimum edge cost of 0 + minimum edge cost of 1) / 2) + (edge cost 0-1)

41
How does it work? To include edge 0-1, we add the edge cost of 0-1, and subtract an edge
weight such that the lower bound remains as tight as possible which would be the sum of the
minimum edges of 0 and 1 divided by 2. Clearly, the edge subtracted can’t be smaller than this.

Dealing with other levels: As we move on to the next level, we again enumerate all possible
vertices. For the above case going further after 1, we check out for 2, 3, 4, …n.

Consider lower bound for 2 as we moved from 1 to 1, we include the edge 1-2 to the tour and
alter the new lower bound for this node.

Lower bound(2) = Old lower bound - ((second minimum edge cost of 1 + minimum edge cost
of 2)/2) + edge cost 1-2).

EXPECTED OUTPUT:

Or Output may be in the following form:

Enter the number of vertices n=4

42
Enter the cost matrix:
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
Enter the Source vertex: 1
Path taken 1→2→4→3 and sum=35.0
Optimal solution with Branch and Bound Technique is =35.0 and
Path is 1→2→4→3

43
Open Ended Problems
Problem 1

Book cartons
A university department is shifting its department library to a more spacious room on a newly
constructed floor. The books from the library have been packed into m cartons, numbered 1, 2,
…, m, containing b1, b2, …, bm books, respectively, and transported to the new library room.
There are k student volunteers available to unpack the m cartons, where k ≤ m. Each carton must
be assigned to a single volunteer, and every volunteer must get a non-empty continuous sequence
of cartons to unpack.
More formally, we need to find numbers 0 = c0 < c1 < c2 < … <ck = m such that volunteer j, 1
≤ j ≤ k unpacks cartons cj-1+1 to cj.
The time each volunteer takes to unpack a carton is directly proportional to the number of books
in the carton. The goal is parallelize the unpacking to finish in the fastest possible time. For this,
we need to assign cartons such that the maximum number of books assigned to any one volunteer
is minimized.

Solution hint
Given a target T, use a greedy strategy to check if there is a legal allocation where no volunteer is
assigned more than T books. Find the optimum T using binary search. Note that if a greedy
strategy finds an allocation achieving target T using k' < k volunteers, this allocation can always
be subdivided to achieve the same target with exactly k volunteers.

Input format
Each test case consists of exactly two lines. The first line has are two integers m and k. The
second line has m integers b1, b2, …,bm separated by spaces.

Output format
Your output should be a single line with the input sequence b1, b2, …,bm divided into
exactly k parts such that the maximum sum in a single part is as small as possible. Use the slash
character ('/') to separate the parts. There must be exactly one space character between any two
successive numbers and between the number and the slash. If there is more than one solution,
print the one that minimizes the work assigned to the first volunteer, then to the second volunteer
etc. Each volunteer must be assigned at least one carton.

44
Test Data:
You may assume that 1 ≤ k ≤ m ≤ 500, always. Also, each carton contains a positive
number of books, which is less than 10,000,000.

Sample Input 1:
9 3

100 200 300 400 500 600 700 800 900

Sample Output 1:
100 200 300 400 500 / 600 700 / 800 900

Sample Input 2:
5 4

100 100 100 100 100

Sample Output 2:
100 / 100 / 100 / 100 100

45
Problem 2
Suppose we are given Indian currency notes of all denominations, e.g.
{1,2,5,10,20,50,100,500,1000}. The problem is to find the minimum number of currency notes
to make the required amount A, for payment. Further, it is assumed that currency notes of each
denomination are available in sufficient numbers, so that one may choose as many notes of the
same denomination as are required for the purpose of using the minimum number of notes to
make the amount A;
Intuitively, to begin with, we pick up a note of denomination D, satisfying the conditions.
i) D ≤ 289 and
ii) if D1 is another denomination of a note such that D1 ≤ 289, then D1 ≤ D.

In other words, the picked-up note’s denomination D is the largest among all the denominations
satisfying condition (i) above. The above-mentioned step of picking note of denomination D,
satisfying the above two conditions, is repeated till either the amount of Rs.289/- is formed or we
are clear that we cannot make an amount or Rs.289/- out of the given denominations.
Case1: To deliver Rs. 289 with minimum number of currency notes, the notes of different
denominations are chosen and rejected as shown below:

The above sequence of steps based on Greedy technique, constitutes an algorithm to solve the
problem.
Case2: Let us consider a hypothetical country in which notes available are of only the
denominations 20, 30 and 50. We are required to collect an amount of 90.
If you apply same approach of case1, show that greedy algorithm fails to deliver a solution to
this (case 2) problem. However, by some other technique, we have the solution to the
problem.

46
Case3: Again, we consider a hypothetical country in which notes available are of the only
denominations 10, 40 and 60. We are required to collect an amount of 80. Show that here Greedy
leads to a solution, but the solution yielded by greedy technique is not optimal.

47
Problem 3
Develop a Hamiltonian Path in an undirected graph is a path that visits each vertex e xactly
once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an
edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. Develop a
program to implement the solution of Travelling Salesman Problem by considering the
Hamiltonian cycle approach.

48
Problem 4
Given two sequences, a subsequence is a sequence that appears in the same relative order, but
not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, „”acefg”, .. etc are
subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences. It is
a classic computer science problem, the basis of file comparison programs and has applications
in bioinformatics. Develop a program to implement the solution of Longest Common Sub-
sequence problem.

Hint: The naive solution for this problem is to generate all sub sequences of both given
sequences and find the longest matching subsequence. This solution is exponential in term of
time complexity. Let us see how this problem possesses both important properties of a
Dynamic Programming (DP) Problem.

Suppose two sequences : X[x1, x2, …. Xm] and Y[y1, y2… yn] are given, then for findings LCS Z

we maintain matrix C[m+1, n+1]

Where each entry C[i,j] is the length of an LCS for sequences Xi and YJ

If i=0 or j=0 then the length of LCS will be zero


Means C[i,0] =0 and C[0, j] =0
Recursive Formula:

49
Problem 5
The exit polls indicate that the sitting MLA is likely to lose the upcoming election. The party
high command instructs him to undertake a padayatra through his constituency to boost his
popularity. To maximize coverage of the constituency, the party decides that he should choose a
circular route that returns to the starting point without using any road twice. The route need not
visit all the towns and villages in the constituency.
Being averse to physical exercise, the MLA would like to minimize the distance that he has to
walk. He has a helicopter at his disposal, so he can begin the padayatra at any town or village.
The task is to help him find the shortest circular route. You are guaranteed that there is always at
least one circular route.

Solution Hint
Given an edge (i,j) with weight W(i,j), the shortest cycle from i to i via j can be found by
temporarily deleting the edge (i,j), finding the shortest path from j to i, and then adding W(i,j) to
the length of this path. Do this systematically to find the shortest cycle in the graph.

Input format
The first line of input is an integer N, 1 ≤ N ≤ 1000, the number of roads in the constituency. The
constituency has no more than 300 towns and villages connected by roads.
The next N lines specify the roads. Each line consists of three space separated integers S, T and
D where S is the starting point of the road, T is the ending point and D is the length of the road.
Each road is a two-way road and is listed exactly once, in one of the two directions.

Output format
A single line with the integer distance around the shortest possible circular route.

Test data
There are at most 300 towns and villages and at most 1000 roads.

Example

50
Sample Input
4
3 1 5
1 2 4
3 2 3
1 5 44

Sample output 1
12

51
Problem 6
Here there be Dragons:
The kingdom is falling into ruin. People live in fear. Dragons pillage, kill, and just generally
cause as much havoc as they possibly can. The king has just sent out a royal decree:
To any man out there who is able to bring me the heads of K dragons, I shall bequeath a
lordship–to him, his sons and his grandsons, till the end of time.
Having seen this royal decree, and knowing that you are capable of killing dragons thanks to
your extensive medieval combat training, you set out on a quest to hunt down the evil creatures.
Being a busy kind of guy, you would like to complete your quest quickly and kill K dragons
through the shortest route.
The kingdom is arranged in a grid with R rows, numbered 0 to R-1, and C columns, numbered 0
to C-1 You start your quest at the top left corner of the grid, (0,0).
The total number of dragons in the kingdom is D, of which you have to kill K. Dragons are very
territorial in nature, so each row of the grid contains at most one dragon. Also, since the kingdom
is situated on a hill, you travel only downwards on the grid, though you may move left or right as
you please.
You are told that no two dragons are on the same row of the grid. Also, no dragon is at position
(0,0).
For example, suppose the grid has 5 rows and 5 columns with 3 dragons, of which you have to
kill any 2. The three dragons are located at (1,4), (2,3) and (4,4), as shown below. In this case,
your shortest route is to take 7 steps and kill the dragons in row 1 and row 2. Killing any other
combination of 2 dragons takes 8 steps, so this is the minimum possible. Note that once you've

52
killed K dragons, you don't incur any cost to return home. You just want to find how long it

takes to do all the killing.

Solution hint
Number the dragons 1,2,…,D in ascending order of rows. Let mindist(i,j) denote the minimum
distance travelled when the jth dragon killed is dragon i. Recall the constraint that there is no
dragon at (0,0). Use dynamic programming to compute mindist(i,j) for all values of i and j, then
find the minimum among mindist(i,K) for all i ≥ K.

Input format
Line 1 : Four space-separated integers, R, C, K and D.
Lines 2 to D+1 : Each line has two-space separated integers r and c, the row and column of the
corresponding dragon.

Output format
A single integer, the minimum total distance travelled to kill K dragons.

Test Data:
• In all subtasks, K ≤ D ≤ R, and, for each dragon position (r,c), 0 ≤ r < R, and 0 ≤ c < C.

• No two dragons will be on the same row.

• No dragon will be at position (0,0).

53
5. List of coordinators and resource persons for Virtual Labs
1. Anant Kumar Jayswal (Coordinator)
2. Sunil Kumar Chowdhary
3. Dr Sumita Gupta
4. Dr Dolly Sharma
5. Dr Garima Agarwal
6. Dr Anjali Goyal
7. Dr Pooja Singh
8. Dr Jyoti Agarwal
9. Dr Richa Tiwari
10. Abhishek Srivastava

*********************

54

You might also like