lOMoARcPSD|28548451
Shri Sukhmani Institute of
Engineering and Technology
LAB
MANUA
L
DEPARTMENT: Computer Science and
Engineering
Name: - Aditya Kumar Mishra
University Roll no: 2006979
Subject: Design Analysis and Algorithm (DAA)
Semester: IV SEM
lOMoARcPSD|28548451
Student Sign…………………. Professor Sign……………
lOMoARcPSD|28548451
I
N
D
E
X
lOMoARcPSD|28548451
SR NO. Date TASK Page no. Teacher Sign
Task 1: Code and analyse solutions to following problem with
strategies. Knap Sack using greedy approach
Output:-
Enter the no. of objects:- 4
lOMoARcPSD|28548451
Enter the wts and profits of each object:- 4 3
25
67
89
Enter the capacityacity of knapsack:- 8
The result vector is:- 1100
Maximum profit is:-12
lOMoARcPSD|28548451
Task 1: Code and analyze solutions to following problem with
strategies. Knap Sack using greedy approach
# include<iostream>
using namespace std;
void knapsack (int n, float weight[], float profit[], float capacity)
{
float x[20], tp = 0;
int i, j, u;
u = capacity; for (i = 0; i
< n; i++)
x[i] = 0.0; for (i
= 0; i < n; i++)
{
if (weight[i] > u)
break;
else { x[i] = 1.0; tp = tp + profit[i];
u = u - weight[i];
}
} if (i < n) x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]); cout<<"\
nThe result vector is:- ";
for (i = 0; i < n; i++)
cout<<x[i];
cout<<"\nMaximum profit is:-"<< tp;
}
int main()
{
float weight[20], profit[20], capacity;
int num, i, j; float
ratio[20], temp;
cout<<"\nEnter the no. of objects:- ";
cin>>num;
cout<<"\nEnter the wts and profits of each object:- ";
for (i = 0; i < num; i++)
{
cin>>weight[i]>>profit[i];
}
cout<<"\nEnter the capacityacity of knapsack:- ";
cin>>capacity; for (i = 0; i < num; i++)
lOMoARcPSD|28548451
{
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (ratio[i] < ratio[j])
{ temp =
ratio[j]; ratio[j]
= ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity); return(0);
}
Task 2: Code and analyse solutions to following problem with
strategies . Knap Sack using dynamic approach
lOMoARcPSD|28548451
Output:-
Enter the number of items: 3
Enter the item’s weight and its value
23
56
17
Enter the capacity of the knapsack : 7
Maximum value in a 0-1 knapsack: 13
lOMoARcPSD|28548451
Task 2: Code and analyse solutions to following problem with
strategies.Knap Sack using dynamic approach
#include<iostream>
using namespace std;
/* Function to find maximum of two integers */
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Returns the maximum value that can be put in a knapsack of capacity W */
int knapSack (int W, int weight [], int value [], int n)
{ int i,
w;
int K[n+1] [W+1];
/* Build table K [][] in bottom up manner */
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0) K[i]
[w] = 0;
else if (weight[i-1] <= w)
K[i][w] = max(value[i-1] + K[i-1] [w-weight[i-1]], K[i-1] [w]);
else
K[i][w] = K[i-1] [w];
}
}
return K[n][W];
}
int main ()
{
int n;
cout << "\nEnter the number of items: ";
cin >> n; int value[n];
int weight[n];
int i;
cout << "\nEnter the item’s weight and its value \n";
for(i = 0; i < n; i++)
{
lOMoARcPSD|28548451
cin >> weight[i] >> value[i];
}
int W;
cout << "\nEnter the capacity of the knapsack : ";
cin >> W;
cout << "\nMaximum value in a 0-1 knapsack: " << knapSack (W, weight,
value, n) << endl;
return 0;
}
lOMoARcPSD|28548451
Task 3: Code and analyse to find an optimal solution to matrix
chain multiplication using dynamic programming.
Ouput:- Enter number of matrices
4
Enter dimensions
Enter d0 :: 4
Enter d1 :: 5
Enter d2 :: 8
Enter d3 :: 9
Enter d4 :: 3
Minimum number of multiplications is 396
lOMoARcPSD|28548451
Task 3: Code and analyse to find an optimal solution to matrix
chain multiplication using dynamic programming.
#include<stdio.h>
#include<limits.h>
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
int MatrixChainMultiplication(int p[], int n)
{
int m[n][n];
int i, j, k, L, q;
for (i=1; i<n; i++)
m[i][i] = 0; //number of multiplications are 0(zero) when there is only one
matrix
//Here L is chain length. It varies from length 2 to length n.
for (L=2; L<n; L++)
{
for (i=1; i<n-L+1; i++)
{ j=
i+L-1;
m[i][j] = INT_MAX; //assigning to maximum value
for (k=i; k<=j-1; k++)
{
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of multiplications found less that number
will be updated.
}
}
}
}
return m[1][n-1]; //returning the final answer which is M[1][n]
}
lOMoARcPSD|28548451
int main()
{
int n,i;
printf("Enter number of matrices\n");
scanf("%d",&n);
n++;
int arr[n];
printf("Enter dimensions \n");
for(i=0;i<n;i++)
{
printf("Enter d%d :: ",i);
scanf("%d",&arr[i]);
}
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainMultiplication(arr, size));
return 0;
}
lOMoARcPSD|28548451
Task 4: Code and analyse to find an optimal solution to TSP using
dynamic programming.
#include<iostream>
using namespace std;
#define MAX 9999
int n=4; // Number of the places want to visit
//Next distan array will give Minimum distance through all the position
int distan[10][10] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int completed_visit = (1<<n) -1;
int DP[16][4];
int TSP(int mark,int position){
if(mark==completed_visit){ // Initially checking whether all
// the places are visited or not
return distan[position][0];
}
if(DP[mark][position]!=-1)
{ return DP[mark][position];
}
//Here we will try to go to every other places to take the minimum
// answer int
answer = MAX;
//Visit rest of the unvisited cities and mark the . Later find the
//minimum shortest path
for(int city=0;city<n;city++){
if((mark&(1<<city))==0){
int newAnswer = distan[position][city] + TSP( mark|(1<<city),city);
answer = min(answer, newAnswer);
}
}
return DP[mark][position] = answer;
} int
main(){
lOMoARcPSD|28548451
/* initialize the DP array */
for(int i=0;i<(1<<n);i++)
{ for(int j=0;j<n;j++){
DP[i][j] = -1;
}
}
cout<<"Minimum Distance Travelled by you is "<<TSP(1,0);
return 0;
}
Output:
lOMoARcPSD|28548451
Task 5: Implement an application of BFS such as to find
connected components of an undirected graph.
Output:-
Enter no of vertices:4
Enter no of edges:4
EDGES
01
02
12
20
Enter initial vertex to traverse from:2
Visitied vertices:2 0 0 0
lOMoARcPSD|28548451
Task 5: Implement an application of BFS such as to find
connected components of an undirected graph.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];
int main()
{
int m;
cout <<"Enter no of vertices:";
cin >> n;
cout <<"Enter no of edges:";
cin >> m; cout <<"\
nEDGES \n";
for(k=1; k<=m; k++)
{ cin
>>i>>j;
cost[i][j]=1;
}
cout <<"Enter initial vertex to traverse from:";
cin >>v;
cout <<"Visitied vertices:";
cout <<v<<" ";
visited[v]=1; k=1;
while(k<n)
{
for(j=1; j<=n; j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{ visit[j]
=1; qu[rare+
+]=j; } v=qu[front+
+]; cout<<v <<" ";
k++;
visit[v]=0; visited[v]=1;
return 0;}
Task 6: Code and analyse to find shortest path in a graph with
positive edges weights using Dijkstra’s algorithm.
Output:-
lOMoARcPSD|28548451
Task 6: Code and analyse to find shortest path in a graph with
positive edges weights using Dijkstra’s algorithm. //
Programmed by: Aditya Mishra
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{ int min = INT_MAX,
min_index; for (int v = 0; v < V;
v++)
if (sptSet[v] == false && dist[v] <= min)
0min = dist[v], min_index = v; return
min_index;
}
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V]; bool sptSet[V]; for (int i
= 0; i < V; i++) dist[i] = INT_MAX,
sptSet[i] = false;
dist[src] = 0;
lOMoARcPSD|28548451
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet); sptSet[u]
= true; for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main()
{
lOMoARcPSD|28548451
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}
lOMoARcPSD|28548451
Task 7: Code and analyse to find shortest path in a graph with
arbitrary edges weights using Bellmen-Ford algorithm.
Output:-
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
lOMoARcPSD|28548451
Task 7: Code and analyse to find shortest path in a graph with
arbitrary edges weights using Bellmen-Ford algorithm.
#include <bits/stdc++.h>
struct Edge { int src,
dest, weight;
}; struct Graph
{ int V, E; struct
Edge* edge;
};
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = new Graph;
graph->V = V; graph->E = E;
graph->edge = new Edge[E];
return graph;
}
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
void BellmanFord(struct Graph* graph, int src)
{
int V = graph->V; int E = graph-
>E; int dist[V]; for (int i = 0; i < V;
i++) dist[i] = INT_MAX; dist[src]
= 0; for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) { int u =
graph->edge[j].src; int v = graph-
>edge[j].dest; int weight = graph-
>edge[j].weight; if (dist[u] !=
INT_MAX
lOMoARcPSD|28548451
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
for (int i = 0; i < E; i++) { int u = graph-
>edge[i].src; int v = graph->edge[i].dest; int
weight = graph->edge[i].weight; if (dist[u] !=
INT_MAX && dist[u] + weight < dist[v])
{ printf("Graph contains negative weight
cycle");
return; }
}
printArr(dist, V);
return;
}
int main()
{
int V = 5;
int E = 8;
struct Graph* graph = createGraph(V, E);
graph->edge[0].src = 0; graph-
>edge[0].dest = 1; graph->edge[0].weight =
-1; graph->edge[1].src = 0; graph-
>edge[1].dest = 2; graph->edge[1].weight =
4; graph->edge[2].src = 1; graph-
>edge[2].dest = 2; graph->edge[2].weight =
3; graph->edge[3].src = 1; graph-
>edge[3].dest = 3; graph->edge[3].weight =
2; graph->edge[4].src = 1; graph-
>edge[4].dest = 4; graph->edge[4].weight =
2; graph->edge[5].src = 3; graph-
>edge[5].dest = 2; graph->edge[5].weight =
5; graph->edge[6].src = 3;
lOMoARcPSD|28548451
graph->edge[6].dest = 1; graph-
>edge[6].weight = 1; graph->edge[7].src =
4; graph->edge[7].dest = 3; graph-
>edge[7].weight = -3; BellmanFord(graph,
0);
return 0;
}
lOMoARcPSD|28548451
Task 8: Code and analyse to find shortest paths in a graph with
arbitrary edge weights using Floyds’-Warshell algorithm.
Output:-
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0
lOMoARcPSD|28548451
Task 8: Code and analyse to find shortest paths in a graph with
arbitrary edge weights using Floyds’-Warshell algorithm.
#include <iostream>
using namespace std;
// defining the number of vertices
#define nV 4 #define INF 999 void
printMatrix(int matrix[][nV]);
// Implementing floyd warshall algorithm
void floydWarshall(int graph[][nV])
{ int matrix[nV][nV], i, j, k;
for (i = 0; i < nV; i++)
for (j = 0; j < nV; j++)
matrix[i][j] = graph[i][j];
// Adding vertices individually for (k = 0; k <
nV; k++) { for (i = 0; i < nV; i++) { for (j
= 0; j < nV; j++) { if (matrix[i][k] +
matrix[k][j] < matrix[i][j]) matrix[i][j] =
matrix[i][k] + matrix[k][j];
}
}
}
printMatrix(matrix);
}
void printMatrix(int matrix[][nV]) {
for (int i = 0; i < nV; i++) { for
(int j = 0; j < nV; j++) { if
(matrix[i][j] == INF)
printf("%4s", "INF");
else
lOMoARcPSD|28548451
printf("%4d", matrix[i][j]);
} printf("\
n");
}
}
int main() {
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}};
floydWarshall(graph);
}
lOMoARcPSD|28548451
Task 9: Code and analyse to find the minimum spanning tree in a
weighted undirected graph using Prims’ algorithm. Output:-
Edge : Weight
0-1: 9
1 - 3 : 19
3 - 4 : 31
3 - 2 : 51
lOMoARcPSD|28548451
Task 9: Code and analyse to find the minimum spanning tree in a
weighted undirected graph using Prims’ algorithm.
#include <cstring>
#include <iostream>
using namespace std;
#define INF 9999999
// number of vertices in grapj
#define V 5
// create a 2d array of size 5x5
//for adjacency matrix to represent graph
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};
int main() {
int no_edge; // number of edge
// create a array to track selected vertex //
selected will become true otherwise false
int selected[V];
// set selected false initially
memset(selected, false, sizeof(selected));
// set number of edge to 0
no_edge = 0;
// the number of egde in minimum spanning tree will be
// always less than (V -1), where V is number of vertices in
//graph
lOMoARcPSD|28548451
// choose 0th vertex and make it true
selected[0] = true; int x; // row
number int y; // col number
// print for edge and weight
cout << "Edge"
<< " : "
<< "Weight";
cout << endl;
while (no_edge < V - 1) {
//For every vertex in the set S, find the all adjacent vertices
// , calculate the distance from the vertex selected at step 1.
// if the vertex is already in the set S, discard it
otherwise //choose another vertex nearest to selected
vertex at step 1. int min = INF; x = 0; y = 0;
for (int i = 0; i < V; i++) {
if (selected[i]) { for (int j
= 0; j < V; j++) {
if (!selected[j] && G[i][j]) { // not in selected and there is an edge
if (min > G[i][j]) { min = G[i][j];
x = i;
y = j;
}
}
}
}
}
cout << x << " - " << y << " : " << G[x][y];
cout << endl; selected[y] = true;
no_edge++;
}
return 0;
}
lOMoARcPSD|28548451
Task 10: Code and analyse to find the minimum spanning tree in a
weighed, undirected graph using Kruskal’s algorithm.
Output:-
Following are the edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
lOMoARcPSD|28548451
Task 10: graph using Code and analyse to find the minimum
spanning tree in a weighed, undirected Kruskal’s algorithm.
#include <bits/stdc++.h>
using namespace std;
class DSU { int* parent;
int* rank;
public:
DSU(int n)
{ parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++)
{ parent[i] = -1;
rank[i] = 1;
}}
// Find function
int find(int i)
{if (parent[i] == -1)
return i;
return parent[i] = find(parent[i]);
}
// union function void
unite(int x, int y)
{ int s1 = find(x); int
s2 = find(y);
if (s1 != s2) { if (rank[s1] < rank[s2])
{ parent[s1] = s2; rank[s2]
+= rank[s1];
}else { parent[s2] =
s1;
lOMoARcPSD|28548451
rank[s1] += rank[s2];
}}}};
class Graph { vector<vector<int> >
edgelist;
int V;
public:
Graph(int V) { this->V = V; }
void addEdge(int x, int y, int w)
{ edgelist.push_back({ w, x, y });}
void kruskals_mst()
{
// 1. Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl; for (auto
edge : edgelist) { int w =
edge[0]; int x = edge[1];
int y = edge[2];
// take that edge in MST if it does form a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}} cout << "Minimum Cost Spanning Tree: "
<< ans;}};
int main()
{
lOMoARcPSD|28548451
/* Let us create following weighted graph
10
0--------1
|\ |
6| 5\ |15
| \|
2--------3
4 */
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
// int n, m;
// cin >> n >> m;
// Graph g(n);
// for (int i = 0; i < m; i++)
// {
// int x, y, w;
// cin >> x >> y >> w;
// g.addEdge(x, y, w);
// }
g.kruskals_mst();
return 0;
}
Task 11: Implementing an application of DFS such as to find the
topological sort of a directed acyclic graph. Output:-
Following is a Topological Sort of the given graph
5 4 2 3 1 0
lOMoARcPSD|28548451
Task 11: Implementing an application of DFS such as to find the
topological sort of a directed acyclic graph.
// A C++ program to print topological
// sorting of a DAG
#include <iostream>
#include <list>
#include <stack>
using namespace std;
// Class to represent a graph
class Graph { // No. of
vertices' int V;
// Pointer to an array containing adjacency listsList
list<int>* adj;
// A function used by topologicalSort void
topologicalSortUtil(int v, bool visited[],
stack<int>& Stack);
public:
// Constructor
Graph(int V);
// function to add an edge to graph
void addEdge(int v, int w);
// prints a Topological Sort of
// the complete graph void
topologicalSort();
};
Graph::Graph(int V)
{
lOMoARcPSD|28548451
this->V = V; adj = new
list<int>[V];
}
void Graph::addEdge(int v, int w)
{
// Add w to v’s list.
adj[v].push_back(w);
}
// A recursive function used by topologicalSort void
Graph::topologicalSortUtil(int v, bool visited[], stack<int>&
Stack)
{
// Mark the current node as visited.
visited[v] = true;
// Recur for all the vertices
// adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!
visited[*i]) topologicalSortUtil(*i, visited,
Stack);
// Push current vertex to stack
// which stores result
Stack.push(v);
// The function to do Topological
Sort. // It uses recursive
topologicalSortUtil() void
Graph::topologicalSort()
{ stack<int> Stack;
lOMoARcPSD|28548451
// Mark all the vertices as not visited
bool* visited = new bool[V]; for (int
i = 0; i < V; i++)
lOMoARcPSD|28548451
visited[i] = false;
// Call the recursive helper function
// to store Topological
// Sort starting from all // vertices one by one
for (int i = 0; i < V; i++) if (visited[i] == false)
topologicalSortUtil(i, visited, Stack);
// Print contents of stack while
(Stack.empty() == false) { cout
<< Stack.top() << " ";
Stack.pop();
}} //
Driver Code
int main()
{
// Create a graph given in the above diagram
Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Following is a Topological Sort of the given "
"graph \n";
// Function Call
g.topologicalSort();
return 0;
}