DAA FILE Taran

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

INDEX

S.No. Practical Name Date Page Remarks


No.
EXPERIMENT 1
AIM : To code and analyze Knapsack problem using Greedy approach.

#include <bits/stdc++.h>

using namespace std;

struct Item {
int value, weight;

Item(int value, int weight)


: profit(profit), weight(weight)
{
}
};

bool cmp(struct Item a, struct Item b)


{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}

double fractionalKnapsack(struct Item arr[],


int N, int size)
{

sort(arr, arr + size, cmp);

int curWeight = 0;

double finalprofit = 0.0;

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

if (curWeight + arr[i].weight <= N) {


curWeight += arr[i].weight;
finalprofit += arr[i].profit;
}
else {
int remain = N - curWeight;
finalprofit += arr[i].profit
* ((double)remain
/ arr[i].weight);
break;
}
}

return finalprofit;
}

int main()
{

int N = 60;

Item arr[] = { { 100, 10 },


{ 280, 40 },
{ 120, 20 },
{ 120, 24 } };

int size = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum profit earned = "


<< fractionalKnapsack(arr, N, size);
return 0;
}

OUTPUT:
AIM – 2 :- To code and analyze Knapsack problem using Dynamic approach.

#include <iostream>
using namespace std;
int max(int x, int y) {
return (x > y) ? x : y;
}
int knapSack(int W, int w[], int v[], int n) {
int i, wt;
int K[n + 1][W + 1];
for (i = 0; i <= n; i++) {
for (wt = 0; wt <= W; wt++) {
if (i == 0 || wt == 0)
K[i][wt] = 0;
else if (w[i - 1] <= wt)
K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);
else
K[i][wt] = K[i - 1][wt];
}
}
return K[n][W];
}
int main() {
cout << "Enter the number of items in a Knapsack:";
int n, W;
cin >> n;
int v[n], w[n];
for (int i = 0; i < n; i++) {
cout << "Enter value and weight for item " << i << ":";
cin >> v[i];
cin >> w[i];
}
cout << "Enter the capacity of knapsack";
cin >> W;
cout << knapSack(W, w, v, n);
return 0;
}
OUTPUT:-
EXPERIMENT - 02
AIM:- Code and analyze to find an optimal solution to matrix chain
multiplication using dynamic programming.
#include <iostream>
using namespace std;
int dp[100][100];

int matrixChainMemoised(int* p, int i, int j)


{
if (i == j)
{
return 0;
}
if (dp[i][j] != -1)
{
return dp[i][j];
}
dp[i][j] = INT_MAX;
for (int k = i; k < j; k++)
{
dp[i][j] = min(
dp[i][j], matrixChainMemoised(p, i, k)
+ matrixChainMemoised(p, k + 1, j)
+ p[i - 1] * p[k] * p[j]);
}
return dp[i][j];
}
int MatrixChainOrder(int* p, int n)
{
int i = 1, j = n - 1;
return matrixChainMemoised(p, i, j);
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
memset(dp, -1, sizeof dp);

cout << "Minimum number of multiplications is "


<< MatrixChainOrder(arr, n);
}
OUTPUT:-
EXPERIMENT -03
AIM:- Code and analyze to find an optimal solution to TSP using
dynamic programming
#include <iostream>
using namespace std;
#define V 4

int travllingSalesmanProblem(int graph[][V], int s)


{

vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);

int min_path = INT_MAX;


do {

int current_pathweight = 0;

int k = s;
for (int i = 0; i < vertex.size(); i++) {
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];
min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}
int main()
{
// matrix representation of graph
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int s = 0;
cout << travllingSalesmanProblem(graph, s) << endl;
return 0;
}

OUTPUT:-
EXPERIMENT -04
AIM:- Implementing an application of DFS such as:

1.) To find the topological sort of a directed acyclic graph


#include <iostream>
#include <list>
#include <stack>
using namespace std;

class Graph {
int V;
list<int>* adj;
void topologicalSortUtil(int v, bool visited[],
stack<int>& Stack);

public:
Graph(int V);
void addEdge(int v, int w);
void topologicalSort();
};

Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w);
}
void Graph::topologicalSortUtil(int v, bool visited[],
stack<int>& Stack)
{
visited[v] = true;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSortUtil(*i, visited, Stack);
Stack.push(v);
}
void Graph::topologicalSort()
{
stack<int> Stack;
bool* visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, Stack);
while (Stack.empty() == false) {
cout << Stack.top() << " ";
Stack.pop();
}
}
int main()
{
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";
g.topologicalSort();

return 0;
}

OUTPUT:-
AIM.2:- To find a path from source to goal in a maze.
#include <cstring>
#include <iostream> #include <stack> using namespace std; #define
N4
#define M 5

class node { public: int x, y; int dir;

node(int i, int j) {
x = i; y = j;

// Initially direction
// set to 0 dir
= 0;
}
};

// maze of n*m matrix int


n = N, m = M;

// Coordinates of food int fx, fy; bool visited[N][M];

bool isReachable(int maze[N][M]) {


// Initially starting at (0, 0).
int i = 0, j = 0;

stack<node> s; node temp(i, j);


s.push(temp); while (!s.empty()) { int d = temp.dir; i = temp.x, j = temp.y;

temp.dir++; s.pop();
s.push(temp);
if (i == fx and j == fy) { return true;
}

// Checking the Up direction. if (d == 0) { if (i - 1 >= 0 and maze[i - 1][j] and


visited[i - 1][j]) { node temp1(i -
1, j);
visited[i - 1][j] = false; s.push(temp1);
}
}
// Checking the left direction else if (d == 1)
{ if (j - 1 >= 0 and maze[i][j - 1] and
visited[i][j - 1]) { node temp1(i, j - 1); visited[i][j - 1] = false; s.push(temp1);
}
}

// Checking the down direction else if (d == 2) { if (i + 1 < n and maze[i + 1][j]


and
visited[i + 1][j]) { node temp1(i +
1, j);
visited[i + 1][j] = false; s.push(temp1);
}
}
// Checking the right direction else if (d == 3) { if (j + 1 < m and maze[i][j + 1]
and
visited[i][j + 1]) { node temp1(i, j + 1); visited[i][j + 1] = false; s.push(temp1);
}
}

// the rat to the Food, retract back


// to the path where the rat came from. else { visited[temp.x][temp.y] = true;
s.pop();
}
}

// If the stack is empty and


// no path is found return false. return false;
}

// Driver code int main()


{
// Initially setting the visited
// array to true (unvisited) memset(visited, true, sizeof(visited));

// Maze matrix
int maze[N][M] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 1 },
{ 0, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1 }
};
// Food coordinates fx = 2; fy = 3;

if (isReachable(maze)) {
cout << "Path Found!" << '\n';
}
else cout << "No Path Found!" << '\n';

return 0;
}

OUTPUT:-
EXPERIMENT -05

Aim: - Write a program to implement Breadth First Search


#include<bits/stdc++.h> using namespace std; class Graph
{ int V;
vector<list<int>> adj;
public:
Graph (int V); void addEdge(int v, int w); void BFS(int s);
};
Graph::Graph(int V)
{ this->V = V; adj.resize(V);
}
void Graph::addEdge(int v, int w)
{ adj[v].push_back(w);
}
void Graph::BFS(int s)
{ vector<bool> visited; visited.resize(V,false);
list<int> queue; visited[s] = true; queue.push_back(s);
while(!queue.empty())
{ s = queue.front(); cout << s << " "; queue.pop_front();
for (auto adjecent: adj[s])
{ if (!visited[adjecent])
{ visited[adjecent] = true; queue.push_back(adjecent);
}
}
} } int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}
Output of the Program 5: -
AIM.2:-To check whether given graph is bipartite or not

#include <iostream>
#include <queue>
#define V 4

using namespace std;

bool isBipartite(int G[][V], int src)


{
int colorArr[V]; for (int i = 0; i < V; ++i)
colorArr[i] = -1;

colorArr[src] = 1; queue <int> q; q.push(src);

while (!q.empty())
{
int u = q.front();
q.pop();

if (G[u][u] == 1)
return false;

// Find all non-colored adjacent vertices


for (int v = 0; v < V; ++v)
{
if (G[u][v] && colorArr[v] == -1)
{
// Assign alternate color to this adjacent v of u
colorArr[v] = 1 - colorArr[u];
q.push(v);
}
else if (G[u][v] && colorArr[v] == colorArr[u])
return false;
}
}

return true;
}

int main()
{
int G[][V] = {{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};

isBipartite(G, 0) ? cout << "Yes" : cout << "No"; return 0;


}

OUTPUT:-
YES
EXPERIMENT .:-6
Aim: - Code and analyse to find shortest path in a graph with positive edge
weights using Dijkstra’s algorithm.
#include <iostream>
using namespace std;
#include <limits.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) min = dist[v], min_index = v; return
min_index;
}

void printSolution(int dist[])

{ cout <<"Vertex \t Distance from Source" << endl; for (int i = 0; i < V; i++)
cout << i << " \t\t"<<dist[i]<< endl;
}
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;
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);
}
int main()

{ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
return 0;

}
Output: -
EXPERIMENT 7:-
Aim: Code and analyse to find shortest path in a graph
with arbitrary edge weights using Bellman-Ford
algorithm.

#include<iostream>

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 && 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;

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;

Output:
EXPERIMENT-8
Aim:- Code and analyse to find shortest path in a graph
with arbitrary weights Floyd’s algorithm.

#include <iostream >


using namespace std;
#define V 4
#define INF 99999

void printSolution(int dist[][V]);


void floydWarshall(int graph[][V])
{

int dist[V][V], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)

dist[i][j] = graph[i][j];
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {

if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] !=


INF))
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

printSolution(dist);

void printSolution(int dist[][V])


{

cout << "The following matrix shows the shortest "


"distances"
" between every pair of
vertices \n"; for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {

if (dist[i][j] == INF)

cout << "INF" << " ";


else
cout << dist[i][j] << " ";
}

cout << endl;

}
}
int main()

{
int graph[V][V] = { { 0, 5, INF, 10 },

{ INF, 0, 3, INF };

{ INF, INF, 0, 1 };

{ INF, INF, INF, 0 } };


floydWarshall(graph); return 0;
}

Output:
EXPERIMENT: 9
Aim: - Code and analyze to find the minimum spanning tree
in a weighted, undirected graph using Prims’ algorithm
#include <iostream>
using namespace std;
#define V 5
bool isValidEdge(int u, int v, vector<bool> inMST)
{ if (u == v)
return false;
if (inMST[u] == false && inMST[v] == false)
return false;
else if (inMST[u] == true && inMST[v] == true)
return false;
return true;
}
void primMST(int cost[][V])
{ vector<bool> inMST(V, false);
inMST[0] = true; int edge_count = 0, mincost = 0; while (edge_count < V
- 1)
{
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (cost[i][j] < min) {
if (isValidEdge(i, j, inMST))
{
min = cost[i][j]; a = i; b = j;
}

}
}
}
if (a != -1 && b != -1) { printf("Edge %d:(%d, %d) cost: %d \n",
edge_count++, a, b, min);
mincost = mincost + min; inMST[b] = inMST[a] = true;
}
}
printf("\n Minimum cost= %d \n", mincost);
}
int main()
{
int cost[][V] =
{
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};

primMST(cost); return 0;
}

Output: -
EXPERIMENT-10
Aim- Code and analyze to find the minimum spanning tree in a
weighted, undirected graph using Kruskals’ algorithm.
#include <iostream>
using namespace std;

#define V 5
int parent[V];
int find(int i)
{ while (parent[i] != i)
i = parent[i];
return i;
}

void union1(int i, int j)


{
int a = find(i);
int b = find(j);
parent[a] = b;
}

void kruskalMST(int cost[][V])


{
int mincost = 0;

for (int i = 0; i < V; i++)


parent[i] = i;

int edge_count = 0;
while (edge_count < V - 1)
{
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (find(i) != find(j) && cost[i][j] < min) {
min = cost[i][j];
a = i; b = j;
}
}
}

union1(a, b);
printf("Edge %d:(%d, %d) cost:%d \n", edge_count++, a, b, min);
mincost += min;
}
printf("\n Minimum cost= %d \n", mincost);
}

// driver program to test above function int main()


{
/* Let us create the following graph
2 3
(0)--(1)--(2)
| /\ |
6| 8/ \5 |7
|/ \|
(3)-------(4) 9 */
int cost[][V] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};

// Print the solution


kruskalMST(cost);

return 0;
}
OUTPUT:
EXPERIMENT -11

AIM:- Coding any real world problem or TSP algorithm using


heuristic technique

#include <bits/stdc++.h>
using namespace std;
#define V 4

int travllingSalesmanProblem(int graph[][V], int s)


{
// store all vertex apart from source vertex
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);
int min_path = INT_MAX;
do {
int current_pathweight = 0;
int k = s;
for (int i = 0; i < vertex.size(); i++)
{
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];

// update minimum
min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

int main()
{
// matrix representation of graph
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 }, {
20, 25, 30, 0 } };
int s = 0;
cout << travllingSalesmanProblem(graph,s)<<endl; return 0 }

OUTPUT:-

80

You might also like