0% found this document useful (0 votes)
9 views25 pages

Task 6 7 Daa New

The document outlines laboratory experiments focused on implementing algorithms using Dynamic Programming and Greedy Techniques, specifically the 0/1 Knapsack problem and Prim's algorithm for finding Minimum Cost Spanning Trees. It includes detailed algorithms, C programming code, and complexity analysis for both tasks. The successful implementation of these algorithms demonstrates their effectiveness in solving optimization problems.

Uploaded by

vtu17493
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views25 pages

Task 6 7 Daa New

The document outlines laboratory experiments focused on implementing algorithms using Dynamic Programming and Greedy Techniques, specifically the 0/1 Knapsack problem and Prim's algorithm for finding Minimum Cost Spanning Trees. It includes detailed algorithms, C programming code, and complexity analysis for both tasks. The successful implementation of these algorithms demonstrates their effectiveness in solving optimization problems.

Uploaded by

vtu17493
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

G.

Laboratory Experiments
Total: 30 Hours (P)
Part – 1

Task 6: Dynamic Programming – Knapsack algorithm


AIM
To Implement 0/1 Knapsack problem using Dynamic Programming and find its
complexity.

ALGORITHM

1. Consider the same cases as mentioned in the recursive approach.


2. In a DP[][] table let’s consider all the possible weights from ‘1’ to ‘W’ as the columns
and weights that can be kept as rows.
3. The state DP[i][j] will denote the maximum value of ‘j-weight’ considering all values
from ‘1 to ith’. So if we consider ‘wi’ (weight in ‘ith’ row) we can fill it in all columns
which have ‘weight values > wi’. Now two possibilities can take place:
a. Fill ‘wi’ in the given column.
b. Do not fill ‘wi’ in the given column.
4. Now we have to take a maximum of these two possibilities, formally if we do not fill
the ‘ith’ weight in the ‘jth’ column then the DP[i][j] state will be the same as DP[i-1][j]
but if we fill the weight, DP[i][j] will be equal to the value of ‘wi’+ value of the column
weighing ‘j-wi’ in the previous row.
5. So we take the maximum of these two possibilities to fill the current state.

Program:

#include <stdio.h>

int max(int a, int b) { return (a > b) ? a : b; }

int knapSack(int W, int wt[], int val[], 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 (wt[i - 1] <= w)

K[i][w] = max(val[i - 1]

+ K[i - 1][w - wt[i - 1]],

K[i - 1][w]);

else

K[i][w] = K[i - 1][w];

return K[n][W];

int main()

int val[] = { 60, 100, 120 };

int wt[] = { 10, 20, 30 };


int W = 50;

int n = sizeof(val) / sizeof(val[0]);

printf("%d", knapSack(W, wt, val, n));

return 0;

Output
220

Time Complexity: O(N * W). where ‘N’ is the number of elements and ‘W’ is capacity.
Auxiliary Space: O(N * W). The use of a 2-D array of size ‘N*W’.
Below is the implementation of the same approach but with optimized space complexity:

Result
Thus Implementing 0/1 Knapsack problem using Dynamic Programming and find its
complexity was learn successfully
Task 7: Greedy Technique – Prim’s algorithm
AIM
To Find Minimum Cost Spanning Tree of a undirected graph using Prim’s algorithm
ALGORITHM
1. Step 1: Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T
5. [END OF LOOP]
6. Step 5: EXIT
Program:

#include<stdio.h>

#include<conio.h>

int a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];

void main()

clrscr();

printf("\n Enter the number of nodes:");

scanf("%d",&n);

printf("\n Enter the adjacency matrix:\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

scanf("%d",&cost[i][j]);

if(cost[i][j]==0)
cost[i][j]=999;

visited[1]=1;

printf("\n");

while(ne<n)

for(i=1,min=999;i<=n;i++)

for(j=1;j<=n;j++)

if(cost[i][j]<min)

if(visited[i]!=0)

min=cost[i][j];

a=u=i;

b=v=j;

if(visited[u]==0 || visited[v]==0)

printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);

mincost+=min;

visited[b]=1;

cost[a][b]=cost[b][a]=999;

}
printf("\n Minimum cost=%d",mincost);

getch();

/* OUTPUT

Enter the number of nodes:6

Enter the adjacency matrix:

063000

602500

320340

053023

004205

000350

Edge 1:(1 3) cost:3

Edge 2:(3 2) cost:2

Edge 3:(3 4) cost:3

Edge 4:(4 5) cost:2

Edge 5:(4 6) cost:3

Minimum cost=13

Test case 1:
Aim:
Assume an undirected graph and find whether the graph is connected or not and then apply
Prim’s algorithm to find MST
Algorithm:
1. Create a Min Heap of size V where V is the number of vertices in the given graph. Every
node of min heap contains vertex number and key value of the vertex.
2. Initialize Min Heap with first vertex as root (the key value assigned to first vertex is 0).
The key value assigned to all other vertices is INF (infinite).
3. While Min Heap is not empty, do following
1. Extract the min value node from Min Heap. Let the extracted vertex be u.
2. For every adjacent vertex v of u, check if v is in Min Heap (not yet included in MST).
If v is in Min Heap and its key value is more than weight of u-v, then update the key
value of v as weight of u-v.

Program:

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a node in adjacency list

struct AdjListNode {

int dest;

int weight;

struct AdjListNode* next;

};

// A structure to represent an adjacency list

struct AdjList {
struct AdjListNode*

head; // pointer to head node of list

};

// A structure to represent a graph. A graph is an array of

// adjacency lists. Size of array will be V (number of

// vertices in graph)

struct Graph {

int V;

struct AdjList* array;

};

// A utility function to create a new adjacency list node

struct AdjListNode* newAdjListNode(int dest, int weight)

struct AdjListNode* newNode

= (struct AdjListNode*)malloc(

sizeof(struct AdjListNode));
newNode->dest = dest;

newNode->weight = weight;

newNode->next = NULL;

return newNode;

// A utility function that creates a graph of V vertices

struct Graph* createGraph(int V)

struct Graph* graph

= (struct Graph*)malloc(sizeof(struct Graph));

graph->V = V;

// Create an array of adjacency lists. Size of array

// will be V

graph->array = (struct AdjList*)malloc(

V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making

// head as NULL

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

graph->array[i].head = NULL;

return graph;

// Adds an edge to an undirected graph

void addEdge(struct Graph* graph, int src, int dest,

int weight)

// Add an edge from src to dest. A new node is added to

// the adjacency list of src. The node is added at the

// beginning

struct AdjListNode* newNode

= newAdjListNode(dest, weight);

newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

// Since graph is undirected, add an edge from dest to

// src also

newNode = newAdjListNode(src, weight);

newNode->next = graph->array[dest].head;

graph->array[dest].head = newNode;

// Structure to represent a min heap node

struct MinHeapNode {

int v;

int key;

};

// Structure to represent a min heap

struct MinHeap {

int size; // Number of heap nodes present currently


int capacity; // Capacity of min heap

int* pos; // This is needed for decreaseKey()

struct MinHeapNode** array;

};

// A utility function to create a new Min Heap Node

struct MinHeapNode* newMinHeapNode(int v, int key)

struct MinHeapNode* minHeapNode

= (struct MinHeapNode*)malloc(

sizeof(struct MinHeapNode));

minHeapNode->v = v;

minHeapNode->key = key;

return minHeapNode;

// A utility function to create a Min Heap

struct MinHeap* createMinHeap(int capacity)


{

struct MinHeap* minHeap

= (struct MinHeap*)malloc(sizeof(struct MinHeap));

minHeap->pos = (int*)malloc(capacity * sizeof(int));

minHeap->size = 0;

minHeap->capacity = capacity;

minHeap->array = (struct MinHeapNode**)malloc(

capacity * sizeof(struct MinHeapNode*));

return minHeap;

// A utility function to swap two nodes of min heap. Needed

// for min heapify

void swapMinHeapNode(struct MinHeapNode** a,

struct MinHeapNode** b)

struct MinHeapNode* t = *a;

*a = *b;
*b = t;

// A standard function to heapify at given idx

// This function also updates position of nodes when they

// are swapped. Position is needed for decreaseKey()

void minHeapify(struct MinHeap* minHeap, int idx)

int smallest, left, right;

smallest = idx;

left = 2 * idx + 1;

right = 2 * idx + 2;

if (left < minHeap->size

&& minHeap->array[left]->key

< minHeap->array[smallest]->key)

smallest = left;

a
if (right < minHeap->size

&& minHeap->array[right]->key

< minHeap->array[smallest]->key)

smallest = right;

if (smallest != idx) {

// The nodes to be swapped in min heap

MinHeapNode* smallestNode

= minHeap->array[smallest];

MinHeapNode* idxNode = minHeap->array[idx];

// Swap positions

minHeap->pos[smallestNode->v] = idx;

minHeap->pos[idxNode->v] = smallest;

// Swap nodes

swapMinHeapNode(&minHeap->array[smallest],

&minHeap->array[idx]);
minHeapify(minHeap, smallest);

// A utility function to check if the given minHeap is empty

// or not

int isEmpty(struct MinHeap* minHeap)

return minHeap->size == 0;

// Standard function to extract minimum node from heap

struct MinHeapNode* extractMin(struct MinHeap* minHeap)

if (isEmpty(minHeap))

return NULL;
// Store the root node

struct MinHeapNode* root = minHeap->array[0];

// Replace root node with last node

struct MinHeapNode* lastNode

= minHeap->array[minHeap->size - 1];

minHeap->array[0] = lastNode;

// Update position of last node

minHeap->pos[root->v] = minHeap->size - 1;

minHeap->pos[lastNode->v] = 0;

// Reduce heap size and heapify root

--minHeap->size;

minHeapify(minHeap, 0);

return root;

}
// Function to decrease key value of a given vertex v. This

// function uses pos[] of min heap to get the current index

// of node in min heap

void decreaseKey(struct MinHeap* minHeap, int v, int key)

// Get the index of v in heap array

int i = minHeap->pos[v];

// Get the node and update its key value

minHeap->array[i]->key = key;

// Travel up while the complete tree is not heapified.

// This is a O(Logn) loop

while (i

&& minHeap->array[i]->key

< minHeap->array[(i - 1) / 2]->key) {

// Swap this node with its parent


minHeap->pos[minHeap->array[i]->v] = (i - 1) / 2;

minHeap->pos[minHeap->array[(i - 1) / 2]->v] = i;

swapMinHeapNode(&minHeap->array[i],

&minHeap->array[(i - 1) / 2]);

// move to parent index

i = (i - 1) / 2;

// A utility function to check if a given vertex

// 'v' is in min heap or not

bool isInMinHeap(struct MinHeap* minHeap, int v)

if (minHeap->pos[v] < minHeap->size)

return true;

return false;

}
// A utility function used to print the constructed MST

void printArr(int arr[], int n)

for (int i = 1; i < n; ++i)

printf("%d - %d\n", arr[i], i);

// The main function that constructs Minimum Spanning Tree

// (MST) using Prim's algorithm

void PrimMST(struct Graph* graph)

int V = graph->V; // Get the number of vertices in graph

int parent[V]; // Array to store constructed MST

int key[V]; // Key values used to pick minimum weight

// edge in cut

// minHeap represents set E


struct MinHeap* minHeap = createMinHeap(V);

// Initialize min heap with all vertices. Key value of

// all vertices (except 0th vertex) is initially

// infinite

for (int v = 1; v < V; ++v) {

parent[v] = -1;

key[v] = INT_MAX;

minHeap->array[v] = newMinHeapNode(v, key[v]);

minHeap->pos[v] = v;

// Make key value of 0th vertex as 0 so that it

// is extracted first

key[0] = 0;

minHeap->array[0] = newMinHeapNode(0, key[0]);

minHeap->pos[0] = 0;
// Initially size of min heap is equal to V

minHeap->size = V;

// In the following loop, min heap contains all nodes

// not yet added to MST.

while (!isEmpty(minHeap)) {

// Extract the vertex with minimum key value

struct MinHeapNode* minHeapNode

= extractMin(minHeap);

int u

= minHeapNode

->v; // Store the extracted vertex number

// Traverse through all adjacent vertices of u (the

// extracted vertex) and update their key values

struct AdjListNode* pCrawl = graph->array[u].head;

while (pCrawl != NULL) {

int v = pCrawl->dest;
// If v is not yet included in MST and weight of

// u-v is less than key value of v, then update

// key value and parent of v

if (isInMinHeap(minHeap, v)

&& pCrawl->weight < key[v]) {

key[v] = pCrawl->weight;

parent[v] = u;

decreaseKey(minHeap, v, key[v]);

pCrawl = pCrawl->next;

// print edges of MST

printArr(parent, V);

}
// Driver program to test above functions

int main()

// Let us create the graph given in above figure

int V = 9;

struct Graph* graph = createGraph(V);

addEdge(graph, 0, 1, 4);

addEdge(graph, 0, 7, 8);

addEdge(graph, 1, 2, 8);

addEdge(graph, 1, 7, 11);

addEdge(graph, 2, 3, 7);

addEdge(graph, 2, 8, 2);

addEdge(graph, 2, 5, 4);

addEdge(graph, 3, 4, 9);

addEdge(graph, 3, 5, 14);

addEdge(graph, 4, 5, 10);

addEdge(graph, 5, 6, 2);

addEdge(graph, 6, 7, 1);
addEdge(graph, 6, 8, 6);

addEdge(graph, 7, 8, 7);

PrimMST(graph);

return 0;

Output
0-1
5-2
2-3
3-4
6-5
7-6
0-7
2-8

Result
Thus Finding Minimum Cost Spanning Tree of a undirected graph using Prim’s
algorithm was learn successfully

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy