Algorithms Lab Manual
Algorithms Lab Manual
16CS311
ALGORITHMS LABORATORY
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 1
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 1
PROGRAM
import java.util.Random;
import java.util.Scanner;
public class Randommergesort {
public static void main(String[] args) {
int a[]= new int[100000];
Scanner in = new Scanner(System.in);
long start, end;
System.out.println("********** MERGE SORT PROGRAM *********");
System.out.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(100);
System.out.println("Array elements to be sorted are");
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");
start=System.nanoTime();
mergesort(a,0,n-1);
end=System.nanoTime();
System.out.println("\nThe sorted elements are");
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 2
16CS311 - ALGORITHMS LABORATORY
}
static void mergesort(int a[], int low, int high){
int mid;
if(low < high){
mid = (low+high)/2;
mergesort(a, low, mid);
mergesort(a, mid+1, high);
merge(a, low, mid, high);
}
}
static void merge(int a[], int low, int mid, int high){
int i, j, h, k, b[]= new int[100000];
h=low; i=low; j=mid+1;
while((h<=mid) && (j<=high)){
if(a[h] < a[j]){
b[i] = a[h]; h=h+1;
}
else
{
b[i] = a[j]; j=j+1;
}
i = i+1;
}
if(h > mid){
for(k=j; k<=high; k++){
b[i] = a[k]; i = i+1;
}
}
else
{
for(k=h; k<=mid; k++){
b[i] = a[k]; i = i+1;
}
}
for(k=low; k<= high; k++)
a[k] = b[k];
}
}
OUTPUT
********** MERGE SORT PROGRAM *********
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 3
16CS311 - ALGORITHMS LABORATORY
4. What is the output of merge sort after the 1st pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
a. 48 25 37 12 57 86 33 92
b. 12 25 33 37 48 57 86 92
c.12 25 33 37 48 57 86 92
d. 25 57 37 48 12 92 33 86
Ans:d
5. What is the output of merge sort after the 2nd pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
a. 48 25 37 12 57 86 33 92
b. 12 25 33 37 48 57 86 92
c.25 37 48 57 12 33 86 92
d. 25 57 37 48 12 92 33 86
Ans:c
6. What is the output of merge sort after the 3rd pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 4
16CS311 - ALGORITHMS LABORATORY
a. 12 25 33 37 48 57 86 92
b. 12 25 33 37 48 57 86 92
c.12 25 33 37 48 57 86 92
d. 25 57 37 48 12 92 33 86
Ans:a
9.Merge sort is based on the divide and conquer strategy.it consists of the following
steps
a. Divide,Recursive and Conquer
b. Divide and Conquer
c. Divide and Recursive
d. None of the above
Ans. a
10.Given two sorted lists of size m,n ,the number of comparisons needed in the worst
case by the merge sort algorithm is
a.mn b.max(m,n) c.min(m,n) d.m+n-1
Ans:d
Each comparison puts 1 element in the final sorted array. So,in the worst case m+n-1
comparisons are needed.
c. 5
d. 7
e. 14
Ans. c
12. If you are provided with two files whose contents are sorted and the requirement is
to copy the contents of both the files into a third file which should be sorted. In this case
which of the sorting techniques can be an appropriate one?
a.Selection sort
b.Bubble sort
c.Merge sort
d.insertion sort
Ans:c
14. What is the output of merge sort after the 1st pass given the following sequence of
numbers : 3,41,52,26,38,57,9,49
a. 3,41,26,52,38,57,9,49
b. 3,41,52,26,38,57,9,49
c. 3,41,52,26,38,57,9,49
d. 3,41,38,26,52,9,49,57
Ans. a
15. What is the output of merge sort after the 2nd pass given the following sequence of
numbers : 3,41,52,26,38,57,9,49
a. 3,26,41,52,38,9,49,57
b. 3,26,41,52,9,38,49,57
c. 3,26,38,9,49,57,41,52
d. 3,26,41,52,38,49,57,9
Ans. b
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 6
16CS311 - ALGORITHMS LABORATORY
There are many ways to traverse graphs. BFS is the most commonly used approach.
BFS is a traversing algorithm where you should start traversing from a selected node
(source or starting node) and traverse the graph layerwise thus exploring the neighbour
nodes (nodes which are directly connected to source node). You must then move
towards the next-level neighbour nodes.
As the name BFS suggests, you are required to traverse the graph breadthwise as
follows:
First move horizontally and visit all the nodes of the current layer
Move to the next layer
ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices.
3. Store the number of vertices in the variable n.
4. Create a adjacency matrix. Using for loop define edges between the nodes are
present or not.
5. Initialize the queue is empty and m[0]=1 denotes the source node is found.
6. From the source node. traverse through the nodes which have edges from the source
node and move these nodes to found not handle queue.
7. Repeat this process untill all nodes are visited.
8. Finally print order of accessed nodes
PROGRAM
import java.io.*;
class bfs
{
public static void main(String args[])throws IOException
{
int i,n,j,k;
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 7
16CS311 - ALGORITHMS LABORATORY
System.out.println("No of vertices:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
int q[]=new int[10];
int m[]=new int[10];
int a[][]=new int[10][10];
for(i=0;i<n;i++)
{
m[i]=0;
}
System.out.println("\n Enter 1 if edge is present,0 if not");
for(i=0;i<n;i++)
{
System.out.println("\n");
for(j=i;j<n;j++)
{
System.out.println("Edge between"+(i+1)+"and"+(j+1)+":");
a[i][j]=Integer.parseInt(br.readLine());
a[j][i]=a[i][j];
}
a[i][i]=0;
}
System.out.println("\n Order of accessed nodes:\n");
q[0]=0;
m[0]=1;
int u;
int node=1;MBCET ME/CSE ADVANCED DATA STRUCTURES LAB –CP7111
int beg1=1;
int beg=0;
while(node>0)
{
u=q[beg];
beg++;
System.out.println(""+(u+1));
node--;
for(j=0;j<n;j++)
{
if(a[u][j]==1)
{
if(m[j]==0)
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 8
16CS311 - ALGORITHMS LABORATORY
m[j]=1;
q[beg1]=j;
node++;
beg1++;
}
}
}
}
}
OUTPUT
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0
Order of accessed nodes: 1
2
3
4
5
6
RESULT
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 9
16CS311 - ALGORITHMS LABORATORY
Thus the java program for performing breadth first search algorithm has been executed
successfully and the output is verified
VIVA VOCE
1. Define a graph.
A graph is a non-linear data structure that represents less relationship between its
adjacent elements. There is no hierarchical relationship between the adjacent elements
in case of graphs.
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.
ALGORITHM
1. Get the number of vertices.
2. To construct edges of graph get 1if edge is present else 0 and repeat the same for all
the vertices of the graph.
3. Store edges in adjacency matrix a[][] and traverse from source node.
4. Initially store m[] with zero .since nodes in graph are not visited. if visited make m[]
as one.
5. To access the order of nodes, for each node check the node is visited or not using m[].
6. In dfs() method ,node visited is marked as one,m[]=1.next node j is traversed by
checking the condition that edge between i and j is present using adjacency matrix a[]
[]=1 and next node to be traversed is not visited, m[]=0.
7. The above step is repeated for all the nodes in the graph.
8. The order of accessed node is outputted.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 11
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import java.io.*;
class dfs
{
static void dfs(int a[][], int m[], int i, int n)
{
int j;
System.out.println("\t" + (i+1));
m[i] = 1;
for(j=0; j<n; j++)
if(a[i][j]==1 && m[j]==0)
dfs(a,m,j,n);
}
if (m[i]==0)
dfs(a,m,i,n);
}
}
OUTPUT
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0
Order of accessed nodes: 1
2
3
4
6
5
RESULT
Thus the java program for performing depth first search algorithm has been executed
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 13
16CS311 - ALGORITHMS LABORATORY
between ith and jth vertex of the graph, such a matrix is referred to as path matrix.
8.Define DFS.
DFS means Depth First search it is like a preorder traversal of a tree. It is continuous
searching for the unvisited nodes in the forward direction based on the recursive
process.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 15
16CS311 - ALGORITHMS LABORATORY
ALGORITHM
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesn’t include all vertices
a) Pick a vertex u which is not there in mstSet and has minimum key value.
b) Include u to mstSet.
c) Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 16
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import java.util.InputMismatchException;
import java.util.Scanner;
int evaluationVertex;
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
this.adjacencyMatrix[source][destination] = adjacencyMatrix[source]
[destination];
}
}
while (getUnsettledCount(unsettled) != 0)
{
evaluationVertex = getMimumKeyVertexFromUnsettled(unsettled);
unsettled[evaluationVertex] = false;
settled[evaluationVertex] = true;
evaluateNeighbours(evaluationVertex);
}
}
04005
40361
03062
06607
51270
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 20
16CS311 - ALGORITHMS LABORATORY
1 : 2 = 4
5 : 3 = 2
2 : 4 = 6
2 : 5 = 1
RESULT
Thus the implementation of Minimum Spanning Tree using Prims Algorithm has been
implemented and output has been verified.
VIVA VOICE
1. What is a spanning tree?
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. A spanning tree does not have cycles and it can not be
disconnected
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 21
16CS311 - ALGORITHMS LABORATORY
ALGORITHM
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 22
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
}
}
}
Collections.sort(edges, new EdgeComparator());
CheckCycle checkCycle = new CheckCycle();
for (Edge edge : edges)
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] = edge.weight;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = edge.weight;
if (checkCycle.checkCycle(spanning_tree, edge.sourcevertex))
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] = 0;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = 0;
edge.weight = -1;
continue;
}
visited[edge.sourcevertex] = 1;
visited[edge.destinationvertex] = 1;
for (int i = 0; i < visited.length; i++)
{
if (visited[i] == 0)
{
finished = false;
break;
} else
{
finished = true;
}
}
if (finished)
break;
}
System.out.println("The spanning tree is ");
for (int i = 1; i <= numberOfVertices; i++)
System.out.print("\t" + i);
System.out.println();
for (int source = 1; source <= numberOfVertices; source++)
{
System.out.print(source + "\t");
for (int destination = 1; destination <= numberOfVertices; destination++)
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 24
16CS311 - ALGORITHMS LABORATORY
System.out.print(spanning_tree[source][destination] + "\t");
}
System.out.println();
}
}
class Edge
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 25
16CS311 - ALGORITHMS LABORATORY
int sourcevertex;
int destinationvertex;
int weight;
}
class CheckCycle
{
private Stack<Integer> stack;
private int adjacencyMatrix[][];
public CheckCycle()
{
stack = new Stack<Integer>();
}
}
}
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacencyMatrix[element][i] >= 1 && visited[i] == 1)
{
if (stack.contains(i))
{
cyclepresent = true;
return cyclepresent;
}
}
if (adjacencyMatrix[element][i] >= 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
adjacencyMatrix[element][i] = 0;// mark as labelled;
adjacencyMatrix[i][element] = 0;
element = i;
i = 1;
continue;
}
i++;
}
stack.pop();
}
return cyclepresent;
}
}
OUTPUT
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 27
16CS311 - ALGORITHMS LABORATORY
068600
6 0 0 5 10 0
800753
657000
0 10 5 0 0 3
003030
1 2 3 4 5 6
1 0 6 0 0 0 0
2 6 0 0 5 0 0
3 0 0 0 7 0 3
4 0 5 7 0 0 0
5 0 0 0 0 0 3
6 0 0 3 0 3 0
RESULT
Thus the implementation of Minimum Spanning Tree using Kruskal Algorithm has been
implemented and output has been verified.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 28
16CS311 - ALGORITHMS LABORATORY
VIVA VOICE
5. How can you create minimum spanning tree using Kruskal’s algorithm?
In Kruskal’s algorithm, for creating minimum spanning tree, sort the edges in the graph
on increasing order by its weight. Take the first edge from the ordered list and add the
source vertex to form a tree. Check whether the destination vertex to the tree. If it
already exists, move to the next edge in the ordered list. Repeat the steps until the tree
contains all the n vertices. The tree produced by the above algorithm, is the minimum
spanning tree.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 29
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 4
Title of the Exercise: Implementation of Dijkstra’s Algorithm
---------------------------------------------------------------------------------------------------------------
DESCRIPTION
Given a graph and a source vertex in graph, find shortest paths from source to all
vertices in the given graph.
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like
Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We
maintain two sets, one set contains vertices included in shortest path tree, other set
includes vertices not yet included in shortest path tree. At every step of the algorithm,
we find a vertex which is in the other set (set of not yet included) and has minimum
distance from source.
Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a
single source vertex to all other vertices in the given graph.
ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices and adjacency matrix.
3. Get the source node and store it in source variable.
4. Create a object for the class DijikstraQueue to access the method dijikstra-algorithm.
5. In this method get the copy of the adjacency matrix. Add the source into the queue.
6. Access getNodewithMinimumDistanceFromQueue,in this get the minimum capacity
vertice and add it to the settle set.
7. Keeping the distance of the node,handle the neighbours of the source and add them to
the queue.After handling the source,remove it from queue.
8. Again handle the nodes that are in queue as the same steps that before we performed.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 30
16CS311 - ALGORITHMS LABORATORY
9. While queue is empty stop the process and then we get the shortest path.
10. Finally, the shortest path from source to each other node is return
PROGRAM
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class DijkstraQueue
{
private int distances[];
private Queue<Integer> queue;
private Set<Integer> settled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraQueue(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
queue = new LinkedList<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{MBCET ME/CSE ADVANCED DATA STRUCTURES LAB –CP7111
V.GOPALAKRISHNAN AP/CSE 23
distances[i] = Integer.MAX_VALUE;
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 31
16CS311 - ALGORITHMS LABORATORY
queue.add(source);
distances[source] = 0;
while (!queue.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromQueue();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromQueue()
{
int min ;
int node = 0;
Iterator<Integer> iterator = queue.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (queue.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
queue.remove(node);
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 32
16CS311 - ALGORITHMS LABORATORY
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
queue.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 33
16CS311 - ALGORITHMS LABORATORY
source = scan.nextInt();
DijkstraQueue dijkstrasQueue = new DijkstraQueue(number_of_vertices);
dijkstrasQueue.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasQueue.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is " + dijkstrasQueue.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT
07002
00102
00040
00500
03850
1 to 1 is 0
1 to 2 is 5
1 to 3 is 6
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 34
16CS311 - ALGORITHMS LABORATORY
1 to 4 is 7
1 to 5 is 2
RESULT
Thus the java program to find shortest path from source to all nodes using dijikstra’s
algorithm in the given graph has been executed successfully and the output is verified..
VIVA VOICE
1: Given a directed weighted graph. You are also given the shortest path from a source
vertex ‘s’ to a destination vertex ‘t’. If weight of every edge is increased by 10 units, does
the shortest path remain same in the modified graph?
The shortest path may change. The reason is, there may be different number of edges in
different paths from s to t. For example, let shortest path be of weight 15 and has 5
edges. Let there be another path with 2 edges and total weight 25. The weight of the
shortest path is increased by 5*10 and becomes 15 + 50. Weight of the other path is
increased by 2*10 and becomes 25 + 20. So the shortest path changes to the other path
with weight as 45.
2: This is similar to above question. Does the shortest path change when weights of all
edges are multiplied by 10?
If we multiply all edge weights by 10, the shortest path doesn’t change. The reason is
simple, weights of all paths from s to t get multiplied by same amount. The number of
edges on a path doesn’t matter. It is like changing unit of weights.
3: Given a directed graph where every edge has weight as either 1 or 2, find the shortest
path from a given source vertex ‘s’ to a given destination vertex ‘t’. Expected time
complexity is O(V+E).
If we apply Dijkstra’s shortest path algorithm, we can get a shortest path in O(E +
VLogV) time. How to do it in O(V+E) time? The idea is to use BFS . One important
observation about BFS is, the path used in BFS always has least number of edges
between any two vertices. So if all edges are of same weight, we can use BFS to find the
shortest path. For this problem, we can modify the graph and split all edges of weight 2
into two edges of weight 1 each. In the modified graph, we can use BFS to find the
shortest path. How is this approach O(V+E)? In worst case, all edges are of weight 2 and
we need to do O(E) operations to split all edges, so the time complexity becomes O(E) +
O(V+E) which is O(V+E).
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 35
16CS311 - ALGORITHMS LABORATORY
all other nodes. Our aim is to visit any two nodes, with a minimum weight, such that the
distance travelled is minimum. One such algorithm is referred as Dijkstra’s shortest path
algorithm. This is very much used in travelling salesman problem
Exercise Number: 5
Title of the Exercise: Implementation of knapsack problem
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a simple java program to implement knapsack problem using greedy
algorithm.
DESCRIPTION
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).
A simple solution is to consider all subsets of items and calculate the total weight and
value of all subsets. Consider the only subsets whose total weight is smaller than W.
From all such subsets, pick the maximum value subset.
1) Optimal Substructure:
To consider all subsets of items, there can be two cases for every item: (1) the item is
included in the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of following
two values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).
2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of
the nth item (including nth item).
If weight of nth item is greater than W, then the nth item cannot be included and case 1
is the only possibility.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 36
16CS311 - ALGORITHMS LABORATORY
ALGORITHM
Assume knapsack holds weight W and items have value vi and weight wi
PROGRAM
import java.util.Scanner;
selected[n] = 1;
w = w - wt[n];
}
else
selected[n] = 0;
}
/** Print finally selected items **/
System.out.println("\nItems selected : ");
for (int i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(i +" ");
System.out.println();
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Knapsack Algorithm Test\n");
/** Make an object of Knapsack class **/
Knapsack ks = new Knapsack();
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 38
16CS311 - ALGORITHMS LABORATORY
OUTPUT
Knapsack Algorithm Test
Items selected :
235
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 39
16CS311 - ALGORITHMS LABORATORY
RESULT
Thus the implementation of knapsack problem using greedy algorithm has been
implemented and output has been verified.
VIVA VOCE
1. Define Greedy method?
i. Greedy method is a popular method for obtaining optimized solutions. The
solution is constructed through a sequence of steps, each expanded in a partially
constructed solution obtained so far, until a complete solution to the problem is reached.
2. Applications of Greedy Method
Knapsack Problem
Prims Algorithm for Minimum Spanning tree.
Kruskal algorithm for Minimum Spanning tree.
Optimal Storage on tapes.
Job Sequencing With Deadlines.
3. What are the choices made by the greedy method?
Feasible i.e., it has to satisfy the problem’s constraints.
Locally optimal, i.e., it has to be the best local choice among all feasible choices available
on those steps.
Irrevocable i.e., once made, it cannot be changed on subsequent steps of the algorithm.
4. What is the objective of Knapsack problem?
i. The objective is to obtain a filling of the knapsack that maximizes the total profit
earned.
5. Define sensible greedy algorithm for knapsack problem?
i. A sensible greedy algorithm for the knapsack problem is based on processing an
input’s items in descending order of their value to weight ratios. For the continuous
version of the problem, this algorithm always yields an exact optimal solution.
6. Define greedy algorithm for the discrete knapsack problem?
Compute the value to weight ratios r=v/w for the items given
Sort the items in non-increasing order of the ratios computed in step1.
Repeat the following operation until no item is left in the sorted list if the current
item on the lists fits into the knapsack, place it in the knapsack otherwise proceed to the
next item.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 40
16CS311 - ALGORITHMS LABORATORY
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 41
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 6
Title of the Exercise: Computing transitive closure using warshall algorithm
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a java program to implement computing transitive closure using
warshall algorithm.
DESCRIPTION
Given a directed graph, find out if a vertex j is reachable from another vertex i for all
vertex pairs (i, j) in the given graph. Here reachable mean that there is a path from
vertex i to j. The reach-ability matrix is called transitive closure of a graph.
The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is
1 if there is an edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.
Floyd Warshall Algorithm can be used, we can calculate the distance matrix dist[V][V]
using Floyd Warshall, if dist[i][j] is infinite, then j is not reachable from i, otherwise j is
reachable and value of dist[i][j] will be less than V.
Instead of directly using Floyd Warshall, we can optimize it in terms of space and time,
for this particular problem. Following are the optimizations:
2) Instead of using arithmetic operations, we can use logical operations. For arithmetic
operation ‘+’, logical and ‘&&’ is used, and for min, logical or ‘||’ is used. (We save time by
a constant factor. Time complexity is same though)
ALGORITHM
• Accept no .of vertices
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 42
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import java.util.Scanner;
}
/** Funtion to display the trasitive closure **/
public void displayTC()
{
System.out.println("\nTransitive closure :\n");
System.out.print(" ");
for (int v = 0; v < V; v++)
System.out.print(" " + v );
System.out.println();
for (int v = 0; v < V; v++)
{
System.out.print(v +" ");
for (int w = 0; w < V; w++)
{
if (tc[v][w])
System.out.print(" * ");
else
System.out.print(" ");
}
System.out.println();
}
}
w.getTC(graph);
w.displayTC();
}
}
OUTPUT
Warshall Algorithm Test
Enter number of vertices
Enter matrix
010001
000000
100100
000000
000100
000010
Transitive closure :
0 1 2 3 4 5
0 * * * * *
1 *
2 * * * * * *
3 *
4 * *
5 * * *
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 45
16CS311 - ALGORITHMS LABORATORY
RESULT
Thus the java program for computing transitive closure using warshall algorithm has
been implemented and output has been verified.
VIVA VOICE
1. Define transitive closure?
The transitive closure of a directed graph with n vertices can be defined as the n-
by-n Boolean matrix T = {tij}, in which the element in the ith row (1<= i <=n) and the jth
column (1<= j <=n) is 1 if there exists a nontrivial directed path from the ith vertex to
the jth vertex otherwise tij is 0.
2. Define warshall’s algorithm?
a. Wharshall’s algorithm constructs the transitive closure of a given digraph with n
vertices through a series of n-by-n Boolean matrices.
b. R (0)…, R (k-1), R (k)…, R (n)
c. Each of these matrices provides certain information about directed paths in the
digraph.
3. How a transitive closure can be generated?
i. Transitive closure can be generated using depth-first or breadth-first search.
Starting from ith vertex, it shows reachable vertices – thus fills the ith line in matrix
Doing so for each vertex as starting point give us a transitive closure matrix.
But it transverse whole digraph several times.
4. What is the rule for generating elements of matrix R (K) from R (k-1)?
a. If an element rij is 1 in R (K-1), it remains 1 in R (k).
b. If an element rij is 0 in R (k-1), it has to be changed to 1 in R (K) if and only if the
element in its row I and column K and the element K and the element in its column J and
row K are both 1’s in R (K-1).
5. What is the efficiency of warshall’s algorithm?
The efficiency of warshall’s algorithm shows that it can be applied to the more general
problem of finding length of the shortest path of the weighted graphs.
6.Define distance matrix?
The element dij in the ith row and the jth column of this matrix indicates the
length of the shortest path from the ith vertex to jth vertex (1<=i, j<=n).
7 . Define Floyd’s algorithm?
Floyd’s algorithm computes the distance matrix of weighted graph with n
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 46
16CS311 - ALGORITHMS LABORATORY
The problem was first formulated in 1930 and is one of the most intensively studied
problems in optimization. It is used as a benchmark for many optimization methods.
Even though the problem is computationally difficult, a large number of heuristics and
exact algorithms are known, so that some instances with tens of thousands of cities can
be solved completely and even problems with millions of cities can be approximated
within a small fraction of 1
ALGORITHM
1. Declare all necessary variables and initialize those variables.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 47
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 48
16CS311 - ALGORITHMS LABORATORY
minindex=inputSet[i];
}
}
return minindex;
}
public void eval()
{
int dummySet[]=new int[n-1];
for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2]; for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 50
16CS311 - ALGORITHMS LABORATORY
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSPExp
{
public static void main(String args[])
{
TSP obj=new TSP();
}
}
OUTPUT
Enter number of nodes: 4
Enter weight of 1 to 2:5
Enter weight of 1 to 3:3
Enter weight of 1 to 4:14
Enter weight of 2 to 1:6
Enter weight of 2 to 3:5
Enter weight of 2 to 4:60
Enter weight of 3 to 1:2
Enter weight of 3 to 2:1
Enter weight of 3 to 4:7
Enter weight of 4 to 1:3
Enter weight of 4 to 2:32
Enter weight of 4 to 3:8
Starting node assumed to be node 1
The tour is 1-2-3-4-1
The final cost is 20
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 51
16CS311 - ALGORITHMS LABORATORY
RESULT
Thus the travelling salesperson problem has been implemented and output has been
verified.
VIVA VOICE
1. What is difference between the dynamic programming and greedy method? NOV
2006
Difference between dynamic programming and greedy method is, it extends the
solution with the best possible decision (not all feasible decisions) at a algorithmic stage
based on the current local optimum and the best decision (not all possible decisions)
made in previous stage. It is not exhaustive, and does not give accurate answer to many
problems. But when it works, it will be the fastest method. The most popular greedy
algorithm is finding the minimal spanning tree as given by Kruskal.
2. Define dynamic programming? (Nov/Dec-2006)
When a problem shows an optimal substructure, i.e. when the optimal solution to
a problem consists of optimal solutions to sub problems (for instance the shortest path
between two vertices on a weighted graph consists of the shortest path between all the
vertices in between) you solve such a problem bottom-up by solving the simplest
problems until you have solved the original problem. This is called a dynamic
programming algorithm.
3. Define binomial coefficient?
The quantity (x + y)9 is binomial if we multiply out the binomial expansion (x + y)2 we
get x2 + 2xy +y2. The coefficients or numerical multipliers of successive terms in these
results are 1, 2, 1.
4. What is the efficiency of binomial algorithm?
The basic operation of this algorithm is addition so the total number of additions made
by this algorithm is based on computing coefficient.
5. What are the three components in dynamic programming solution?
Formulate the answer as a recurrence relation or recursive algorithm
Show that the number of different instances of your recurrence is bounded by a
polynomial.
Specify an order of evaluation for recurrence so you always have what you need.
6. Define the principle of optimality? (MAY/JUNE 06, NOV/DEC 06)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 52
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 8
Title of the Exercise: N Queens Problem
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to place the N number of Queens in a N*N chess board.
DESCRIPTION
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that
no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where
'Q' and '.' both indicate a queen and an empty space respectively.
ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of Queens and store it in the variable N.
3. Call enumerate() method and create array a and initialize it.
4. By using the method overloading concept, the queens one by one.
5. Then by using is consistent method to check that no two queens should be placed in
the
diagonal or in same row or column.
6. Place the queens in the board by satisfying the conditions and mark the remaining
place as *.
7. Finally the output will display all the possible ways to place the queens in chess board
PROGRAM
import java.util.*;
public class Queens
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 53
16CS311 - ALGORITHMS LABORATORY
{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 54
16CS311 - ALGORITHMS LABORATORY
}
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
System.out.print("Enter no. of Queens: ");
int N = S.nextInt();
enumerate(N);
}
}
OUTPUT
Enter the number of elements in array
10
Enter 10 integer(s)
2
3
1
5
6
7
8
9
4
0
Enter the number to search
6
6 is present at location 5.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 55
16CS311 - ALGORITHMS LABORATORY
RESULT
Thus the java program for N queens problem has been implemented and output has
been verified.
VIVA VOICE
1) What is the algorithm that used to solve combinational problem?
Back tracking
Branch and bounding
2) Define back tracking?
Back tracking constructs its state space tree in the depth first search fashion in the
majority of its applications. If the sequence of choices represented by a current node of
the state space tree can be developed further without violating the problem’s
constraints, considering the first remaining legitimate option for the next component
does it.
3) Define the basic idea of backtracking.
The basic idea of backtracking is to build up a vector, one component at a time and to
test whether the vector being formed has any chance of success.
4) Define 8 queens problem?
Given a 8*8 chessboard and 8 queens we have to find a position for each queen such that
no queen may be taken by any another queen i.e., such that every row, column and
diagonal contains at most one queen
5) Define n queen’s problem?
The n queen’s problem is to place n queens on an n-by-n chessboard so that no two
queens attack each other by being in the same row or in the same column or in the same
diagonal.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 56
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 9
Vertex coloring is the starting point of the subject, and other coloring problems can be
transformed into a vertex version. For example, an edge coloring of a graph is just a
vertex coloring of its line graph, and a face coloring of a plane graph is just a vertex
coloring of its dual. However, non-vertex coloring problems are often stated and studied
as is. That is partly for perspective, and partly because some problems are best studied
in non-vertex form, as for instance is edge coloring.
The convention of using colors originates from coloring the countries of a map, where
each face is literally colored. This was generalized to coloring the faces of a graph
embedded in the plane. By planar duality it became coloring the vertices, and in this
form it generalizes to all graphs. In mathematical and computer representations, it is
typical to use the first few positive or nonnegative integers as the "colors". In general,
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 57
16CS311 - ALGORITHMS LABORATORY
one can use any finite set as the "color set". The nature of the coloring problem depends
on the number of colors but not on what they are.
ALGORITHM
1. Get the number of vertices and store it in the variable n.
2. Create adjacency matrix,using for loop defines edges between the nodes are present
or not.
3. Get the number of colors available and store it in the variable m.
4. mcolouring() method calls another method nextvalue().
5. This method checks the next node value, here nodes are arranged as per the number
of colors available.
6. No two nodes have the same color nearly.
7. For n number of nodes the solution of the graph coloring is displayed.
8. If no solutions are present for the given input then it displays no possible solutions.
PROGRAM
import java.util.Scanner;
public class GraphColoring
{
private int V, numOfColors;
private int[] color;
private int[][] graph;
try
{
solve(0);
System.out.println("No solution");
}
catch (Exception e)
{
System.out.println("\nSolution exists ");
display();
}
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 58
16CS311 - ALGORITHMS LABORATORY
gc.graphColor(graph, c);
}
}
OUTPUT
Enter the Number of Vertices
10
Enter matrix
0100010000
1010001000
0101000100
0010100010
1001000001
1000000110
0100000011
0010010001
0001011000
0000101100
Solution exists
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 60
16CS311 - ALGORITHMS LABORATORY
Colors : 1 2 1 2 3 2 1 3 3 2
RESULT
Thus the Java program for graph coloring has been implemented and output has been
verified.
VIVA VOICE
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 61
16CS311 - ALGORITHMS LABORATORY
Exercise Number: 10
Title of the Exercise: Subset generation
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a simple java program to implement subset generation.
DESCRIPTION
A subset describes a selection of objects, where the order among them does not matter.
Many of the algorithmic problems in this catalog seek the best subset of a group of
things: vertex cover seeks the smallest subset of vertices to touch each edge in a graph;
knapsack seeks the most profitable subset of items of bounded total size; and set
packing seeks the smallest subset of subsets that together cover each item exactly once.
There are 2 power n subsets of an n-element set, including the empty set as well as the
set itself. This grows exponentially, but at a considerably smaller rate than the n!
permutations of n items. Indeed, since 2 power, a brute-force search through all subsets
of 20 elements is easily manageable, although by n=30 equls 1,073,741,824, so you will
certainly be pushing things.
By definition, the relative order among the elements does not distinguish different
subsets. Thus {125} power is the same as {215} . However, it is a very good idea to
maintain your subsets in a sorted or canonical order, in order to speed up such
operations as testing whether two subsets are identical or making them look right when
printed.
ALGORITHM
Algorithm SumOfSub (s, k, r)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 62
16CS311 - ALGORITHMS LABORATORY
PROGRAM
import static java.lang.Math.pow;
public class subSet {
/**
* @param args
*/
void subset(int num,int n, int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]=new int[10];
int x[]=new int[10];
int n,d,sum,present=0;
int j;
System.out.println("enter the number of elements of set");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 63
16CS311 - ALGORITHMS LABORATORY
System.out.print("}="+d);
System.out.println();
}
}
if(present==0)
System.out.println("Solution does not exists");
}
}
OUTPUT
enter the number of elements of set
5
enter the elements of set
12568
enter the positive integer sum
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 64
16CS311 - ALGORITHMS LABORATORY
9
Subset={1,8,}=9
Subset={1,2,6,}=9
RESULT
Thus the java program for subset generation has been implemented and output has
been verified.
VIVA VOICE
1. Define subset sum problem?
Subset sum problem is to find a subset of a given set S= (s1, s2….sn) of n positive
integers whose sum is equal to a given positive integer d. For example s= {1, 2, 6} and {1,
8}
2. What is the subset-sum problem?
Find a subset of a given set S= {s1,………, sn} of ‘n’ positive integers whose sum is equal
to a given positive integer‘d’.
3. What are the tricks used to reduce the size of the state-space tree?
The various tricks are.
1. Exploit the symmetry often present in combinatorial problems. So some solutions can
be obtained by the reflection of others. This cuts the size of the tree by about half.
2. Reassign values to one or more components of a solution.
3. Rearranging the data of a given instance.
4. How will you terminate a search path in a state space of a branch and bound
algorithm? (NOV/DEC 2009)
The value of the node’s bound is not better than the value of the best solution
seen so for
The node represents no feasible solutions because the constrains of the problem
are already violated
The subset of the feasible solutions represented by the node consists of a single
point
5. Define state space tree?
State space tree is a tree in which the root represents an initial state before the search
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 65
16CS311 - ALGORITHMS LABORATORY
begins. The node in the first level in the tree represent the choices made for the first
component of a solution, the nodes of the second level represent the choices for the
second component and so on.
6. What does promising mean?
A node in a state space tree is said to be promising if it corresponds to a partially
constructed solution that may still lead to a complete solution.
7. What are the branch and bound techniques that can be best fit?
a. Traveling salesman problem
b. Knapsack problem
8. Where the backtracking technique can be best fit?
a. N – queen problem
b. Hamiltonian problem
c. Subset problem
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 66