CP4161 Ads Lab Final

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

DEPARTMENT

OF

COMPUTER SCIENCE AND ENGINEERING

FIRST YEAR

REGULATION 2021

RECORD NOTE

ME- COMPUTER SCIENCE AND ENGINEERING

CP4161 -ADVANCED DATA STRUCTURES AND ALGORITHMS

LABORATORY

ACADEMIC YEAR :: 2024-2025


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Bonafide Certificate
REGISTER NO:

Certified that this bonafide record of the work done by the candidate

Mr/Ms…………….…..………..………. of ME -COMPUTER SCIENCE & ENGINEERING

in CP4161 -ADVANCED DATA STRUCTURES AND ALGORITHMS LABORATORY

during the academic year 2024-2025

Signature of Lab-In-Charge Head of the Department

Submitted for the practical Examination held on …………..………….

Internal Examiner External Examiner


l O M oA R c P S D | 1 2 2 0 8 0 2 6

CP4161 ADVANCED DATA STRUCTURES AND ALGORITHMS LTPC


LABORATORY 0042

OBJECTIVES:
 To acquire the knowledge of using advanced tree structures
 To learn the usage of heap structures
 To understand the usage of graph structures and spanning trees
 To understand the problems such as matrix chain multiplication, activity selection and
Huffman coding
 To understand the necessary mathematical abstraction to solve problems.

LISTOF EXPERIMENTS:
1:Implementation of recursive function for tree traversal and Fibonacci
2: Implementation of iteration function for tree traversal and Fibonacci
3: Implementation of Merge Sort and Quick Sort
4:Implementation of a Binary Search Tree
5: Red-Black Tree Implementation
6:Heap Implementation
7:Fibonacci Heap Implementation
8: Graph Traversals
9:Spanning Tree Implementation
10:Shortest Path Algorithms (Dijkstra's algorithm, Bellman Ford Algorithm)
11: Implementation of Matrix Chain Multiplication
12:ActivitySelectionandHuffmanCodingImplementation
HARDWARE/SOFTWAREREQUIREMENTS
1. 64-bit Open source Linux or its derivative
2. Open Source C++Programming tool like G++/GCC
TOTAL:60 PERIODS
l O M oA R c P S D | 1 2 2 0 8 0 2 6

TABLE OF CONTENTS

NAME OF THE LAB:


NAME OF THE STAFF INCHARGE:

PAGE STAFF
MARK
EX.NO DATE NAME THE EXPERIMENTS NO. SIGN

Implementation of recursive function for tree traversal


1 and Fibonacci
2 Implementation of iteration function for tree
traversal and Fibonacci
3 Implementation of Merge Sort and Quick Sort

4 Implementation of a Binary Search Tree

5 Red-Black Tree Implementation

6 Heap Implementation
7 Fibonacci Heap Implementation

8 Graph Traversals

9 Spanning Tree Implementation

10 Shortest Path Algorithms (Dijkstra's algorithm,


Bellman Ford Algorithm)
11 Implementation of Matrix Chain Multiplication

Activity Selection and Huffman Coding


12 Implementation
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO: 1 Implementation of Recursive Function For Tree


Traversal And Fibonacci
DATE:

AIM:
Write to implementation of recursive function for tree traversal and fibonacci
using C++.

ALGORITHM:

STEP1: First, visit all the nodes in the left sub tree

STEP2:Then the root node

STEP3:Visit all the nodes in the right sub tree


STEP4: Read n value for computing n thterm in Fibonacci series

STEP5: call Fibonacci (n)

STEP6: Print the nth term

STEP7: End

SOURCE CODE:
#include <iostream>
using namespace std;

struct Node {
int data;
struct Node *left, *right;
Node(int data) {
this->data = data;
left = right = NULL;
}
};

// Preorder traversal
void preorderTraversal(struct Node* node) {
if (node == NULL)
return;

cout << node->data << "->";


preorderTraversal(node->left);
preorderTraversal(node->right);
l O M oA R c P S D | 1 2 2 0 8 0 2 6

// Postorder traversal
void postorderTraversal(struct Node* node) {
if (node == NULL)
return;

FIBONACCI

#include <iostream>
using namespace std;
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
return 0;
}

OUTPUT:
5 -> 12 -> 6 -> 1 -> 9

Enter the number of terms of series : 15


Fibonnaci Series :
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

RESULT:
Thus implementation of recursive function for tree traversal and fibonacci using C++
Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO: 2 Implementation of Iteration Function for Tree Traversal


andFibonacci
DATE:

AIM:

Write to implementation of iteration function for tree traversal and fibonacci


using C++.

ALGORITHM:

STEP1: First, visit all the nodes in the left subtree

STEP2:Then the root node

STEP3:Visit all the nodes in the right subtree


STEP4: Read n value for computing nthterm in Fibonacci series

STEP5: call Fibonacci (n)

STEP6: Print the nthterm

STEP7: End

SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
// Tree Node
struct Node {
int data;
Node *left, *right;

Node(int data)
{
this->data = data;
this->left = this->right = NULL;
}
};
void preorderIterative(Node* root)
{
if (root == NULL)
return;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

stack<Node*> st;

Node* curr = root;


while (!st.empty() || curr != NULL) {
while (curr != NULL) {
cout << curr->data << " ";

if (curr->right)
st.push(curr->right);

curr = curr->left;
}
if (st.empty() == false) {
curr = st.top();
st.pop();
}
}
}
int main()
{
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->left->left = new Node(70);
root->left->right = new Node(50);
root->right->left = new Node(60);
root->left->left->right = new Node(80);

preorderIterative(root);

return 0;
}

FIBONACCI
#include <iostream>
using namespace std;
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}
int main() {
int num;
cout << "Enter the number : ";
cin >> num;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout << "\nThe fibonacci series : " ;


fib(num);
return 0;
}

return 0;
}

OUTPUT:
10 20 40 70 80 50 30 60

Enter the number : 10


The fibonacci series : 0 1 1 2 3 5 8 13 21 34

RESULT:
Thus implementation of iteration function for tree traversal and fibonacci
using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO: 3 Implementation of Merge Sort and Quick Sort


DATE:

AIM:

Write to implementation of Merge Sort and Quick Sort using C++.

ALGORITHM:
MERGE SORT

STEP1:Take input of data.


STEP2:Call Merge Sort() function.
STEP3:Recursively split the array into two equal parts.
STEP4:Split them until we get at most one element in both half.
STEP5:Combine the result by invoking Merge().
STEP6:It combines the individually sorted data from low to mid and mid+1 to high.
STEP7:Return to main and display the result.
STEP8:Exit.

SOURCE CODE:

#include <bits/stdc++.h>
using namespace std;
void Merge(int *a, int low, int high, int mid)
{
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

while (i <= mid && j <= high)


{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

while (i <= mid)


{
temp[k] = a[i];
k++;
i++;
}

while (j <= high)


{
temp[k] = a[j];
k++;
j++;
}

for (i = low; i <= high; i++)


{
a[i] = temp[i-low];
}
}
void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);

Merge(a, low, high, mid);


}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

MergeSort(arr, 0, n-1);

// Printing the sorted data.


l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout<<"\nSorted Data ";


for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}
OUTPUT: MERGE SORT
Enter the number of data element to be sorted: 10
Enter element 1: 23
Enter element 2: 987
Enter element 3: 45
Enter element 4: 65
Enter element 5: 32
Enter element 6: 9
Enter element 7: 475
Enter element 8: 1
Enter element 9: 17
Enter element 10: 3

Sorted Data ->1->3->9->17->23->32->45->65->475->987

QUICK SORT:

ALGORITHM:

Step 1: Take two elements low and high

Step 2: Make low store the starting index of the array

Step 3: Make high store the last index of the array

Step 4: Take a variable j and initialize it to low

Step 5: Take pivot as the last element is the array

Step 6: Traverse through the entire array using the variable i and compare each
element with pivot

Step 7: If arr[i] < pivot then increment j and swap element as position j and i

Step 8: Increment i by 1

Step 9: When the loop terminates, return j – 1

PROGRAM:

#include

using namespace std;


l O M oA R c P S D | 1 2 2 0 8 0 2 6

void swap(int arr[] , int pos1, int pos2){

int temp;

temp = arr[pos1];

arr[pos1] = arr[pos2];

arr[pos2] = temp;

int partition(int arr[], int low, int high, int pivot){

int i = low;

int j = low;

while( i <= high){

if(arr[i] > pivot){

i++;

else{

swap(arr,i,j);

i++;

j++;

return j-1;

void quickSort(int arr[], int low, int high){

if(low < high){

int pivot = arr[high];

int pos = partition(arr, low, high, pivot);


l O M oA R c P S D | 1 2 2 0 8 0 2 6

quickSort(arr, low, pos-1);

quickSort(arr, pos+1, high);

int main()

int n ;

cout << " enter the size of array";

cin>>n;

int arr[n];

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

cin>> arr[i];

quickSort(arr, 0 , n-1);

cout<<"The sorted array is: ";

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

cout<< arr[i]<<"\t";

OUTPUT : QUICKSORT

Enter the size of array5


32
21
54
76
45
The sorted array is: 21 32 45 54 76
l O M oA R c P S D | 1 2 2 0 8 0 2 6

RESULT:

Thus implementation of Merge sort and Quick sort using C++ Successfully
completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EXNO: 4 Implementation of a Binary Search Tree

DATE:

AIM:

Write to implementation of Binary Search Tree using C++.

ALGORITHM:

STEP1: The right sub-tree of a node has a key greater than to its parent nodes.
STEP2:The left sub-tree of a node has a key lesser than to its parent node's.
STEP3:All key values are distinct.
STEP4:Each node cannot have more than two children.
STEP5: End

SOURCE CODE:
# include <iostream>
# include <cstdlib>
using namespace std;
struct node
{
int info;
struct node *left;
struct node *right;
}*root;
class BST
{
public:
void find(int, node **, node **);
void insert(node *, node *);
void del(int);
void case_a(node *,node *);
void case_b(node *,node *);
void case_c(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
void display(node *, int);
BST()
{
root = NULL;
}
};
int main()
{
int choice, num;
BST bst;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

node *temp;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

while (1)
{
cout<<" ---------------- "<<endl;
cout<<"Operations on BST"<<endl;
cout<<" ---------------- "<<endl;
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Inorder Traversal"<<endl;
cout<<"4.Preorder Traversal"<<endl;
cout<<"5.Postorder Traversal"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<"Enter the number to be inserted : ";
cin>>temp->info;
bst.insert(root, temp);
case 2:
if (root == NULL)
{
cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>num;
bst.del(num);
break;
case 3:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(root);
cout<<endl;
break;
case 5:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(root);
cout<<endl;
break;
case 6:
cout<<"Display BST:"<<endl;
bst.display(root,1);
cout<<endl;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

break;
case 7:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}
void BST::find(int item, node **par, node **loc)
{
node *ptr, *ptrsave;
if (root == NULL)
{
*loc = NULL;
*par = NULL;
return;
}
if (item == root->info)
{
*loc = root;
*par = NULL;
return;
}
if (item < root->info)
ptr = root->left;
else
ptr = root->right;
ptrsave = root;
while (ptr != NULL)
{
if (item == ptr->info)
{
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (item < ptr->info)
ptr = ptr->left;
else
ptr = ptr->right;
}
*loc = NULL;
*par = ptrsave;
}
void BST::insert(node *tree, node *newnode)
{
if (root == NULL)
{
root = new node;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

root->info = newnode->info;
root->left = NULL;
root->right = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
}
void BST::del(int item)
{
node *parent, *location;
if (root == NULL)
{
cout<<"Tree empty"<<endl;
return;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

find(item, &parent, &location);


if (location == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (location->left == NULL && location->right == NULL)
case_a(parent, location);
if (location->left != NULL && location->right == NULL)
case_b(parent, location);
if (location->left == NULL && location->right != NULL)
case_b(parent, location);
if (location->left != NULL && location->right != NULL)
case_c(parent, location);
free(location);
}
void BST::case_a(node *par, node *loc )
{
if (par == NULL)
{
root = NULL;
}
else
{
if (loc == par->left)
par->left = NULL;
else
par->right = NULL;
}
}
void BST::case_b(node *par, node *loc)
{
node *child;
if (loc->left != NULL)
child = loc->left;
else
child = loc->right;
if (par == NULL)
{
root = child;
}
else
{
if (loc == par->left)
par->left = child;
else
par->right = child;
}
}
void BST::case_c(node *par, node *loc)
l O M oA R c P S D | 1 2 2 0 8 0 2 6

{
node *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->right;
while (ptr->left != NULL)
{
ptrsave = ptr;
ptr = ptr->left;
}
suc = ptr;
parsuc = ptrsave;
if (suc->left == NULL && suc->right == NULL)
case_a(parsuc, suc);
else
case_b(parsuc, suc);
if (par == NULL)
{
root = suc;
}
else
{
if (loc == par->left)
par->left = suc;
else
par->right = suc;
}
suc->left = loc->left;
suc->right = loc->right;
}
void BST::preorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}

void BST::inorder(node *ptr)


{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->info<<" ";
inorder(ptr->right);
}
}
void BST::postorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->info<<" ";
}
}
void BST::display(node *ptr, int level)
{
int i;
if (ptr != NULL)
{
display(ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
display(ptr->left, level+1);
}
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

OUTPUT:
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 8
Root Node is Added

RESULT:
Thus implementation of Binary Search using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EXNO: 5 Red-Black Tree Implementation


DATE:

AIM:

Write to implementation of Red - Black Tree using C++.

ALGORITHM:

STEP1: A node is either red or black.


STEP2: The root is black.
SREP3: All leaves (NIL) are black. All leaves are of the same color as the root.
STEP4: Every red node must have two black child nodes, and therefore it must have
a black parent.
STEP5: Every path from a given node to any of its descendant NIL nodes contains
the same number of black nodes.

SOURCE CODE:

#include <bits/stdc++.h>
using namespace std;
struct node
{
int key;
node *parent;
char color;
node *left;
node *right;
};
class RBtree
{
node *root;
node *q;
public :
RBtree()
{
q=NULL;
root=NULL;
}
void insert();
void insertfix(node *);
void leftrotate(node *);
void rightrotate(node *);
void del();
l O M oA R c P S D | 1 2 2 0 8 0 2 6

node* successor(node *);


void delfix(node *);
void disp();
void display( node *);
void search();
};
void RBtree::insert()
{
int z,i=0;
cout<<"\nEnter key of the node to be inserted: ";
cin>>z;
node *p,*q;
node *t=new node;
t->key=z;
t->left=NULL;
t->right=NULL;
t->color='r';
p=root;
q=NULL;
if(root==NULL)
{
root=t;
t->parent=NULL;
}
else
{
while(p!=NULL)
{
q=p;
if(p->key<t->key)
p=p->right;
else
p=p->left;
}
t->parent=q;
if(q->key<t->key)
q->right=t;
else
q->left=t;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

insertfix(t);
}
void RBtree::insertfix(node *t)
{
node *u;
if(root==t)
{
t->color='b';
return;
}
while(t->parent!=NULL&&t->parent->color=='r')
{
node *g=t->parent->parent;
if(g->left==t->parent)
{
if(g->right!=NULL)
{
u=g->right;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g;
}
}
else
{
if(t->parent->right==t)
{
t=t->parent;
leftrotate(t);
}
t->parent->color='b';
g->color='r';
rightrotate(g);
}
}
else
{
l O M oA R c P S D | 1 2 2 0 8 0 2 6

if(g->left!=NULL)
{
u=g->left;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g;
}
}
else
{
if(t->parent->left==t)
{
t=t->parent;
right
rotate(t);
}
t->parent->color='b';
g->color='r'; left
rotate(g);
}
}
root->color='b';
}
}

void RBtree::del()
{
if(root==NULL)
{
cout<<"\nEmpty Tree." ;
return ;
}
int x;
cout<<"\nEnter the key of the node to be deleted: ";
cin>>x;
node *p;
p=root;
node *y=NULL;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

node *q=NULL;
int found=0;
while(p!=NULL&&found==0)
{
if(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
if(found==0)
{
cout<<"\nElement Not Found.";
return ;
}
else
{
cout<<"\nDeleted Element: "<<p->key;
cout<<"\nColour: ";
if(p->color=='b')
cout<<"Black\n";
else
cout<<"Red\n";

if(p->parent!=NULL)
cout<<"\nParent: "<<p->parent->key;
else
cout<<"\nThere is no parent of the node. ";
if(p->right!=NULL)
cout<<"\nRight Child: "<<p->right->key;
else
cout<<"\nThere is no right child of the node. ";
if(p->left!=NULL)
cout<<"\nLeft Child: "<<p->left->key;
else
cout<<"\nThere is no left child of the node. ";
l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout<<"\nNode Deleted.";
if(p->left==NULL||p->right==NULL)
y=p;
else
y=successor(p);
if(y->left!=NULL)
q=y->left;
else
{
if(y->right!=NULL)
q=y->right;
else
q=NULL;
}
if(q!=NULL)
q->parent=y->parent;
if(y->parent==NULL)
root=q;
else
{
if(y==y->parent->left)
y->parent->left=q;
else
y->parent->right=q;
}
if(y!=p)
{
p->color=y->color;
p->key=y->key;
}
if(y->color=='b')
delfix(q);
}
}

void RBtree::delfix(node *p)


{
node *s;
while(p!=root&&p->color=='b')
{
l O M oA R c P S D | 1 2 2 0 8 0 2 6

if(p->parent->left==p)
{
s=p->parent->right;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
leftrotate(p->parent);
s=p->parent->right;
}
if(s->right->color=='b'&&s->left->color=='b')
{
s->color='r';
p=p->parent;
}
els
e
{

if(s->right->color=='b')
{
s->left->color=='b';
s->color='r';
rightrotate(s);
s=p->parent->right;
}
s->color=p->parent->color;
p->parent->color='b';
s->right->color='b';
leftrotate(p->parent);
p=root;
}
}
else
{

s=p->parent->left;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
rightrotate(p->parent);
s=p->parent->left;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

}
if(s->left->color=='b'&&s->right->color=='b')
{
s->color='r';
p=p->parent;
}
else
{
if(s->left->color=='b')
{
s->right->color='b';
s->color='r';
leftrotate(s);
s=p->parent->left;
}
s->color=p->parent->color;
p->parent->color='b';
s->left->color='b';
rightrotate(p->parent);
p=root;
}
}
p->color='b';
root->color='b';
}
}

void RBtree::leftrotate(node *p)


{
if(p->right==NULL)
return ;
else
{
node *y=p->right;
if(y->left!=NULL)
{
p->right=y->left;
y->left->parent=p;
}
els
e
l O M oA R c P S D | 1 2 2 0 8 0 2 6

p->right=NULL;
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
}

y->left=p;
p->parent=y;
}
}
void RB tree::right rotate(node *p)
{
if(p->left==NULL)
return ;
else
{
node *y=p->left;
if(y->right!=NULL)
{
p->left=y->right;
y->right->parent=p;
}
else
p- >left=NULL;
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

}
y->right=p;
p->parent=y;
}
}

node* RB tree::successor(node *p)


{
node *y=NULL;
if(p->left!=NULL)
{
y=p->left;
while(y->right!=NULL)
y=y->right;
}
else
{
y=p->right;
while(y->left!=NULL)
y=y->left;
}
return y;
}

void RBtree::disp()
{
display(root);
}
void RBtree::display(node *p)
{
if(root==NULL)
{
cout<<"\nEmpty Tree.";
return ;
}
if(p!=NULL)
{
cout<<"\n\t NODE: ";
cout<<"\n Key: "<<p->key;
cout<<"\n Colour: ";
l O M oA R c P S D | 1 2 2 0 8 0 2 6

if(p->color=='b')
cout<<"Black";
else
cout<<"Red";
if(p->parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else
cout<<"\n There is no right child of the node. ";
if(p->left!=NULL)
cout<<"\n Left Child: "<<p->left->key;
else
cout<<"\n There is no left child of the node. ";
cout<<endl;
if(p->left)
{
cout<<"\n\nLeft:\n";
display(p->left);
}
/*else
cout<<"\nNo Left Child.\n";*/
if(p->right)
{
cout<<"\n\nRight:\n";
display(p->right);
}
/*else
cout<<"\nNo Right Child.\n"*/
}
}
void RBtree::search()
{
if(root==NULL)
{
cout<<"\nEmpty Tree\n" ;
return ;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

int x;
cout<<"\n Enter key of the node to be searched: ";
cin>>x;
node *p=root;
int found=0;
while(p!=NULL&& found==0)
{
if(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
if(found==0)
cout<<"\nElement Not Found.";
else
{
cout<<"\n\t FOUND NODE: ";
cout<<"\n Key: "<<p->key;
cout<<"\n Colour: ";
if(p->color=='b')
cout<<"Black";
else
cout<<"Red";
if(p->parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else
cout<<"\n There is no right child of the node. ";
if(p->left!=NULL)
cout<<"\n Left Child: "<<p->left->key;
else
cout<<"\n There is no left child of the node. ";
l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout<<endl;

}
}
int main()
{
int ch,y=0;
RBtree obj;
do
{
cout<<"\n\t RED BLACK TREE " ;
cout<<"\n 1. Insert in the tree ";
cout<<"\n 2. Delete a node from the tree";
cout<<"\n 3. Search for an element in the tree";
cout<<"\n 4. Display the tree ";
cout<<"\n 5. Exit " ;
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1 : obj.insert();
cout<<"\nNode Inserted.\n";
break;
case 2 : obj.del();
break;
case 3 : obj.search();
break;
case 4 : obj.disp();
break;
case 5 : y=1;
break;
default : cout<<"\nEnter a Valid Choice.";
}
cout<<endl;

}while(y!=1);
return 1;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

OUTPUT:
1. Insert in the tree
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice: 1
Enter key of the node to be inserted: 4
Node Inserted.

RESULT:
Thus implementation of Red-Black Tree using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EXNO: 6 Heap Implementation

DATE:

AIM:

Write to implementation of Heap using C++.

ALGORITHM:

STEP1: To insert an element in the tree

STEP2:we insert the element at the end of the array.

STEP3:We will compare the data of the node with the Parent node.
STEP4: we will repeat the same process till we hit the root node.

STEP5: End

SOURCE CODE:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <iterator>
using namespace std;
class Heap
{
private:
vector <int> heap;
int left(int parent);
int right(int parent);
int parent(int child);
void heapifyup(int index);
void heapifydown(int index);
public:
Heap()
{}
void Insert(int element);
void DeleteMin();
int ExtractMin();
void DisplayHeap();
int Size();
};
int Heap::Size()
{
return heap.size();
}
void Heap::Insert(int element)
l O M oA R c P S D | 1 2 2 0 8 0 2 6

{
heap.push_back(element);
heapifyup(heap.size() -1);
}
void Heap::DeleteMin()
{
if (heap.size() == 0)
{
cout<<"Heap is Empty"<<endl;
return;
}
heap[0] = heap.at(heap.size() - 1);
heap.pop_back();
heapifydown(0);
cout<<"Element Deleted"<<endl;
}

int Heap::ExtractMin()
{
if (heap.size() == 0)
{
return -1;
}
else
return heap.front();
}

void Heap::DisplayHeap()
{
vector <int>::iterator pos = heap.begin();
cout<<"Heap --> ";
while (pos != heap.end())
{
cout<<*pos<<" ";
pos++;
}
cout<<endl;
}

int Heap::left(int parent)


{
int l = 2 * parent + 1;
if(l < heap.size())
return l;
else
return -1;
}

int Heap::right(int parent)


{
l O M oA R c P S D | 1 2 2 0 8 0 2 6

int r = 2 * parent + 2;
if(r < heap.size())
return r;
else
return -1;
}

int Heap::parent(int child)


{
int p = (child - 1)/2;
if(child == 0)
return -1;
else
return p;
}
void Heap::heapifyup(int in)
{
if (in >= 0 && parent(in) >= 0 && heap[parent(in)] > heap[in])
{
int temp = heap[in];
heap[in] = heap[parent(in)];
heap[parent(in)] = temp;
heapifyup(parent(in));
}
}

void Heap::heapifydown(int in)


{

int child = left(in);


int child1 = right(in);
if (child >= 0 && child1 >= 0 && heap[child] > heap[child1])
{
child = child1;
}
if (child > 0)
{
int temp = heap[in];
heap[in] = heap[child];
heap[child] = temp;
heapifydown(child);
}
}
int main()
{
Heap h;
while (1)
{
cout<<" ----------------- "<<endl;
cout<<"Operations on Heap"<<endl;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout<<" ----------------- "<<endl;


cout<<"1.Insert Element"<<endl;
cout<<"2.Delete Minimum Element"<<endl;
cout<<"3.Extract Minimum Element"<<endl;
cout<<"4.Print Heap"<<endl;
cout<<"5.Exit"<<endl;
int choice, element;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the element to be inserted: ";
cin>>element;
h.Insert(element);
break;
case 2:
h.DeleteMin();
break;
case 3:
cout<<"Minimum Element: ";
if (h.ExtractMin() == -1)
{
cout<<"Heap is Empty"<<endl;
}
else
cout<<"Minimum Element: "<<h.ExtractMin()<<endl;
break;
case 4:
cout<<"Displaying elements of Hwap: ";
h.DisplayHeap();
break;
case 5:
exit(1);
default:
cout<<"Enter Correct Choice"<<endl;
}
}
return 0;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

OUTPUT:
1. Insert Element
2. Delete Minimum Element
3.Extract Minimum Element
4.Print Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 7

RESULT:
Thus implementation of Heap using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EXNO: 7 Fibonacci Heap Implementation


DATE:

AIM:

Write to implementation of Fibonacci heap using C++.

ALGORITHM:

STEP1: Create a new node ‘x’.


STEP2:Check whether heap H is empty or not.
STEP3:If H is empty then:
STEP4:Make x as the only node in the root list.
STEP5:Set H(min) pointer to x.
STEP6:Else: Insert x into root list and update H(min).
STEP7: End

SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;

struct node
{
int n;
int degree;
node* parent;
node* child;
node* left;
node* right;
char mark;
char C;
};
/*
* Class Declaration
*/
class FibonacciHeap
{
private:
int nH;
node *H;
public:
node* InitializeHeap();
int Fibonnaci_link(node*, node*, node*);
node *Create_node(int);
node *Insert(node *, node *);
node *Union(node *, node *);
node *Extract_Min(node *);
int Consolidate(node *);
l O M oA R c P S D | 1 2 2 0 8 0 2 6

int Display(node *);


node *Find(node *, int);
int Decrease_key(node *, int, int);
int Delete_key(node *,int);
int Cut(node *, node *, node *);
int Cascase_cut(node *, node *);
FibonacciHeap()
{
H = InitializeHeap();
}
};
/*
* Initialize Heap
*/
node* FibonacciHeap::InitializeHeap()
{
node* np;
np = NULL;
return np;
}
/*
* Create Node
*/
node* FibonacciHeap::Create_node(int value)
{
node* x = new node;
x->n = value;
return x;
}
/*
* Insert Node
*/
node* FibonacciHeap::Insert(node* H, node* x)
{
x->degree = 0;
x->parent = NULL;
x->child = NULL;
x->left = x;
x->right = x;
x->mark = 'F';
x->C = 'N';
if (H != NULL)
{
(H->left)->right = x;
x->right = H;
x->left = H->left;
H->left = x;
if (x->n < H->n)
H = x;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

else
{
H = x;
}
nH = nH + 1;
return H;
}
/*
* Link Nodes in Fibonnaci Heap
*/
int FibonacciHeap::Fibonnaci_link(node* H1, node* y, node* z)
{
(y->left)->right = y->right;
(y->right)->left = y->left;
if (z->right == z)
H1 = z;
y->left = y;
y->right = y;
y->parent = z;
if (z->child == NULL)
z->child = y;
y->right = z->child;
y->left = (z->child)->left;
((z->child)->left)->right = y;
(z->child)->left = y;
if (y->n < (z->child)->n)
z->child = y;
z->degree++;
}
/*
* Union Nodes in Fibonnaci Heap
*/
node* FibonacciHeap::Union(node* H1, node* H2)
{
node* np;
node* H = InitializeHeap();
H = H1;
(H->left)->right = H2;
(H2->left)->right = H;
np = H->left;
H->left = H2->left;
H2->left = np;
return H;
}
/*
* Display Fibonnaci Heap
*/
int FibonacciHeap::Display(node* H)
{
node* p = H;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

if (p == NULL)
{
cout<<"The Heap is Empty"<<endl;
return 0;
}
cout<<"The root nodes of Heap are: "<<endl;
do
{
cout<<p->n;
p = p->right;
if (p != H)
{
cout<<"-->";
}
}
while (p != H && p->right != NULL);
cout<<endl;
}
/*
* Extract Min Node in Fibonnaci Heap
*/
node* FibonacciHeap::Extract_Min(node* H1)
{
node* p;
node* ptr;
node* z = H1;
p = z;
ptr = z;
if (z == NULL)
return z;
node* x;
node* np;
x = NULL;
if (z->child != NULL)
x = z->child;
if (x != NULL)
{
ptr = x;
do
{
np = x->right;
(H1->left)->right = x;
x->right = H1;
x->left = H1->left;
H1->left = x;
if (x->n < H1->n)
H1 = x;
x->parent = NULL;
x = np;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

while (np != ptr);


}
(z->left)->right = z->right;
(z->right)->left = z->left;
H1 = z->right;
if (z == z->right && z->child == NULL)
H = NULL;
else
{
H1 = z->right;
Consolidate(H1);
}
nH = nH - 1;
return p;
}
/*
* Consolidate Node in Fibonnaci Heap
*/
int FibonacciHeap::Consolidate(node* H1)
{
int d, i;
float f = (log(nH)) / (log(2));
int D = f;
node* A[D];
for (i = 0; i <= D; i++)
A[i] = NULL;
node* x = H1;
node* y;
node* np;
node* pt = x;
do
{
pt = pt->right;
d = x->degree;
while (A[d] != NULL)
{
y = A[d];
if (x->n > y->n)
{
np = x;
x = y;
y = np;
}
if (y == H1)
H1 = x;
Fibonnaci_link(H1, y, x);
if (x->right == x)
H1 = x;
A[d] = NULL;
d = d + 1;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

}
A[d] = x;
x = x->right;
}
while (x != H1);
H = NULL;
for (int j = 0; j <= D; j++)
{
if (A[j] != NULL)
{
A[j]->left = A[j];
A[j]->right =A[j];
if (H != NULL)
{
(H->left)->right = A[j];
A[j]->right = H;
A[j]->left = H->left;
H->left = A[j];
if (A[j]->n < H->n)
H = A[j];
}
else
{
H = A[j];
}
if(H == NULL)
H = A[j];
else if (A[j]->n < H->n)
H = A[j];
}
}
}

/*
* Decrease key of Nodes in Fibonnaci Heap
*/
int FibonacciHeap::Decrease_key(node*H1, int x, int k)
{
node* y;
if (H1 == NULL)
{
cout<<"The Heap is Empty"<<endl;
return 0;
}
node* ptr = Find(H1, x);
if (ptr == NULL)
{
cout<<"Node not found in the Heap"<<endl;
return 1;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

if (ptr->n < k)
{
cout<<"Entered key greater than current key"<<endl;
return 0;
}
ptr->n = k;
y = ptr->parent;
if (y != NULL && ptr->n < y->n)
{
Cut(H1, ptr, y);
Cascase_cut(H1, y);
}
if (ptr->n < H->n)
H = ptr;
return 0;
}
/*
* Cut Nodes in Fibonnaci Heap
*/
int FibonacciHeap::Cut(node* H1, node* x, node* y)
{
if (x == x->right)
y->child = NULL;
(x->left)->right = x->right;
(x->right)->left = x->left;
if (x == y->child)
y->child = x->right;
y->degree = y->degree - 1;
x->right = x;
x->left = x;
(H1->left)->right = x;
x->right = H1;
x->left = H1->left;
H1->left = x;
x->parent = NULL;
x->mark = 'F';
}

/*
* Cascade Cutting in Fibonnaci Heap
*/
int FibonacciHeap::Cascase_cut(node* H1, node* y)
{
node* z = y->parent;
if (z != NULL)
{
if (y->mark == 'F')
{
y->mark = 'T';
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

else
{
Cut(H1, y, z);
Cascase_cut(H1, z);
}
}
}

/*
* Find Nodes in Fibonnaci Heap
*/
node* FibonacciHeap::Find(node* H, int k)
{
node* x = H;
x->C = 'Y';
node* p = NULL;
if (x->n == k)
{
p = x;
x->C = 'N';
return p;
}
if (p == NULL)
{
if (x->child != NULL )
p = Find(x->child, k);
if ((x->right)->C != 'Y' )
p = Find(x->right, k);
}
x->C = 'N';
return p;
}
/*
* Delete Nodes in Fibonnaci Heap
*/
int FibonacciHeap::Delete_key(node* H1, int k)
{
node* np = NULL;
int t;
t = Decrease_key(H1, k, -5000);
if (!t)
np = Extract_Min(H);
if (np != NULL)
cout<<"Key Deleted"<<endl;
else
cout<<"Key not Deleted"<<endl;
return 0;
}
/*
* Main Contains Menu
l O M oA R c P S D | 1 2 2 0 8 0 2 6

*/
int main()
{
int n, m, l;
FibonacciHeap fh;
node* p;
node* H;
H = fh.InitializeHeap();
while (1)
{
cout<<" "<<endl;
cout<<"Operations on Binomial heap"<<endl;
cout<<" "<<endl;
cout<<"1)Insert Element in the heap"<<endl;
cout<<"2)Extract Minimum key node"<<endl;
cout<<"3)Decrease key of a node"<<endl;
cout<<"4)Delete a node"<<endl;
cout<<"5)Display Heap"<<endl;
cout<<"6)Exit"<<endl;
cout<<"Enter Your Choice: ";
cin>>l;
switch(l)
{
case 1:
cout<<"Enter the element to be inserted: ";
cin>>m;
p = fh.Create_node(m);
H = fh.Insert(H, p);
break;
case 2:
p = fh.Extract_Min(H);
if (p != NULL)
cout<<"The node with minimum key: "<<p->n<<endl;
else
cout<<"Heap is empty"<<endl;
break;
case 3:
cout<<"Enter the key to be decreased: ";
cin>>m;
cout<<"Enter new key value: ";
cin>>l;
fh.Decrease_key(H, m, l);
break;
case 4:
cout<<"Enter the key to be deleted: ";
cin>>m;
fh.Delete_key(H, m);
break;
case 5:
cout<<"The Heap is: "<<endl;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

fh.Display(H);
break;
case 6:
exit(1);
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}

OUTPUT:

1)Insert Element in the heap


2)Extract Minimum key node
3)Decrease key of a node
4)Delete a node
5)Display Heap
6)Exit
Enter Your Choice: 1
Enter the element to be inserted: 9

RESULT:
Thus implementation Fibonacci heap using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO: 8 Graph Traversals

DATE:

AIM:

Write to implementation of Graph Traversals using C++.

ALGORITHM:

STEP 1: Insert the root node or starting node of a tree or a graph in the stack.
STEP2: Pop the top item from the stack and add it to the visited list.
STEP 3: Find all the adjacent nodes of the node marked visited and add the ones
that are not yet visited, to the stack.
STEP 4: Repeat steps 2 and 3 until the stack is empty
STEP5: End

SOURCE CODE:

Breadth First Search

#include <iostream>
#include <list>
#include <memory>

class Graph
{
int _V;
bool _directed;
std::unique_ptr< std::list<int> > adj;

public:
Graph(int V, bool directed);
void AddEdge(int v, int w);
void BreadthFirstSearch(int s);
};

Graph::Graph(int V, bool directed) : adj(new std::list<int>[V])


{
_V = V;
_directed = directed;
}

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


{
std::list<int>* adjacency = adj.get();
adjacency[v].push_back(w);

if (!_directed)
{
l O M oA R c P S D | 1 2 2 0 8 0 2 6

adjacency[w].push_back(v);
}
}

void Graph::BreadthFirstSearch(int s)
{
bool *visited = new bool[_V];
for(int i = 0; i < _V; i++)
visited[i] = false;

std::list<int> queue;

visited[s] = true;
queue.push_back(s);

std::list<int>::iterator i;

while(!queue.empty())
{
s = queue.front();
std::cout << s << " ";
queue.pop_front();

for(i = (adj.get())[s].begin(); i != (adj.get())[s].end(); ++i)


{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}

int main()
{
Graph g(7, true);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(0, 3);
g.AddEdge(1, 0);
g.AddEdge(1, 5);
g.AddEdge(2, 5);
g.AddEdge(3, 0);
g.AddEdge(3, 4);
g.AddEdge(4, 6);
g.AddEdge(5, 1);
ddEdge(6, 5);

std::cout << "Breadth First Traversal from vertex 2:\n";


l O M oA R c P S D | 1 2 2 0 8 0 2 6

readthFirstSearch(2);

return 0;
}

Depth First Search

#include <iostream>
#include <list>
#include <memory>

class Graph
{
private:
int _V;
bool _directed;
std::unique_ptr< std::list<int> > adj;
void DFSUtil(int v, bool visited[]);

public:
Graph(int V, bool directed);
void AddEdge(int v, int w);
void DepthFirstSearch(int s);
};

Graph::Graph(int V, bool directed) : adj(new std::list<int>[V])


{
_V = V;
_directed = directed;
}

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


{
std::list<int>* adjacency = adj.get();
adjacency[v].push_back(w);

if (!_directed)
{
adjacency[w].push_back(v);
}
}

void Graph::DFSUtil(int v, bool visited[])


{
visited[v] = true;
std::cout << v << " ";

std::list<int>::iterator i;
for (i = (adj.get())[v].begin(); i != (adj.get())[v].end(); ++i)
if (!visited[*i])
l O M oA R c P S D | 1 2 2 0 8 0 2 6

DFSUtil(*i, visited);
}

void Graph::DepthFirstSearch(int v)
{
std::unique_ptr<bool[]> visited(new bool[_V]);

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


visited[i] = false;

DFSUtil(v, visited.get());
}

int main()
{
Graph g(7, true);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(0, 3);
g.AddEdge(1, 0);
g.AddEdge(1, 5);
g.AddEdge(2, 5);
g.AddEdge(3, 0);
g.AddEdge(3, 4);
g.AddEdge(4, 6);
g.AddEdge(5, 1);
g.AddEdge(6, 5);

std::cout << "Depth First Traversal starting from vertex 2:\n";


g.DepthFirstSearch(2);

return 0;
}

OUTPUT:
Breadth First Traversal from vertex 2: 2 5 1 0 3 4 6

Depth First Traversal starting from vertex 2: 2 5 1 0 3 4 6

RESULT:
Thus implementation of Graph traversal using C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EXNO: 9 Spanning Tree Implementation

DATE:

AIM:

Write to implementation of Spanning Tree using C++.

ALGORITHM:

STEP1: Sort all the edges in non-decreasing order of their weight.


STEP2: 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.
STEP3: Repeat step#2 until there are (V-1) edges in the spanning tree
STEP4: End

SOURCE CODE:
#include<bits/stdc++.h>
using namespace std;
<int, int> iPair;

struct Graph
{
int V, E;
vector< pair<int, iPair> > edges;

Graph(int V, int E)
{
this->V = V;
this->E = E;
}

void addEdge(int u, int v, int w)


{
edges.push_back({w, {u, v}});
}

int kruskalMST();
};

struct DisjointSets
{
int *parent, *rnk;
int n;

DisjointSets(int n)
{
l O M oA R c P S D | 1 2 2 0 8 0 2 6

this->n = n;
parent = new int[n+1];
rnk = new int[n+1];
for (int i = 0; i <= n; i++)
{
rnk[i] = 0;

parent[i] = i;
}
}

int find(int u)
{
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}

void merge(int x, int y)


{
x = find(x), y = find(y);

if (rnk[x] > rnk[y])


parent[y] = x;
else // If rnk[x] <= rnk[y]
parent[x] = y;

if (rnk[x] == rnk[y])
rnk[y]++;
}
};

int Graph::kruskalMST()
{
int mst_wt = 0; // Initialize result

sort(edges.begin(), edges.end());

DisjointSets ds(V);

vector< pair<int, iPair> >::iterator it;


for (it=edges.begin(); it!=edges.end(); it++)
{
int u = it->second.first;
int v = it->second.second;

int set_u = ds.find(u);


int set_v = ds.find(v);

if (set_u != set_v)
l O M oA R c P S D | 1 2 2 0 8 0 2 6

{
cout << u << " - " << v << endl;

mst_wt += it->first;

ds.merge(set_u, set_v);
}
}

return mst_wt;
}

int main()
{
int V = 9, E = 14;
Graph g(V, E);

g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);

cout << "Edges of MST are \n";


int mst_wt = g.kruskalMST();

cout << "\nWeight of MST is " << mst_wt;

return 0;

}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

OUTPUT:
Edges of MST are
6-7
2-8
5-6
0-1
2-5
2-3
0-7
3-4

Weight of MST is 37

RESULT:
Thus implementation of Spanning Tree C++ Successfully completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO: 10 Shortest Path Algorithms (Dijkstra's Algorithm, Bellman


FordAlgorithm)
DATE:

AIM:

Write to implementation of Shortest Path Algorithm using C++.

ALGORITHM:
STEP1: Initialize distances from the source to all vertices as infinite and
distance to source itself as 0.
STEP2: for each edge a->b of the graph
STEP3: If dis[b] > dis[a] + weight of edge (a->b) then
STEP4: dis[b] = dis[a] + weight of edge (a->b)
STEP5: repeat step 2 for nv-1 times (nv is no. of vertices).
STEP6: If dis[b] > dis[a] + weight of edge (a->b) then
STEP7: report a negative cycle in the graph.

SOURCE CODE:
#include<iostream>
#include<climits>
using namespace std;

int miniDist(int distance[], bool Tset[]) // finding minimum distance


{
int minimum=INT_MAX,ind;

for(int k=0;k<6;k++)
{
if(Tset[k]==false && distance[k]<=minimum)
{
minimum=distance[k];
ind=k;
}
}
return ind;
}

void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix


{
int distance[6]; // // array to calculate the minimum distance for each node
bool Tset[6];// boolean array to mark visited and unvisited for each node

for(int k = 0; k<6; k++)


{
distance[k] = INT_MAX;
Tset[k] = false;
l O M oA R c P S D | 1 2 2 0 8 0 2 6

distance[src] = 0; // Source vertex distance is set 0

for(int k = 0; k<6; k++)


{
int m=miniDist(distance,Tset);
Tset[m]=true;
for(int k = 0; k<6; k++)
{
// updating the distance of neighbouring vertex
if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX &&
distance[m]+graph[m][k]<distance[k])
distance[k]=distance[m]+graph[m][k];
}
}
cout<<"Vertex\t\tDistance from source vertex"<<endl;
for(int k = 0; k<6; k++)
{
char str=65+k;
cout<<str<<"\t\t\t"<<distance[k]<<endl;
}
}

int main()
{
int graph[6][6]={
{0, 1, 2, 0, 0, 0},
{1, 0, 0, 5, 1, 0},
{2, 0, 0, 2, 3, 0},
{0, 5, 2, 0, 2, 2},
{0, 1, 3, 2, 0, 1},
{0, 0, 0, 2, 1, 0}};
DijkstraAlgo(graph,0);
return 0;
}

OUTPUT :
Vertex Distance from source
A 0
B 1
C 2
D 4
E 2
F 3
l O M oA R c P S D | 1 2 2 0 8 0 2 6

SOURCE CODE:
#include<iostream>
#define MAX 10
using namespace std;
typedef struct edge
{
int src;
int dest;
int wt;
}edge;
void bellman_ford(int nv,edge e[],int src_graph,int ne)
{
int u,v,weight,i,j=0;
int dis[MAX];

for(i=0;i<nv;i++)
{
dis[i]=999;
}

dis[src_graph]=0;

for(i=0;i<nv-1;i++)
{
for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;

if(dis[u]!=999 && dis[u]+weight < dis[v])


{
dis[v]=dis[u]+weight;
}
}

for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;

if(dis[u]+weight < dis[v])


{
cout<<"\n\nNEGATIVE CYCLE PRESENT..!!\n";
return;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

cout<<"\nVertex"<<" Distance from source";


for(i=1;i<=nv;i++)
{
cout<<"\n"<<i<<"\t"<<dis[i];
}
}
int main()
{
int nv,ne,src_graph;
edge e[MAX];

cout<<"Enter the number of vertices: ";


cin>>nv;

printf("Enter the source vertex of the graph: ");


cin>>src_graph;

cout<<"\nEnter no. of edges: ";


cin>>ne;

for(int i=0;i<ne;i++)
{
cout<<"\nFor edge "<<i+1<<"=>";
cout<<"\nEnter source vertex :";
cin>>e[i].src;
cout<<"Enter destination vertex :";
cin>>e[i].dest;
cout<<"Enter weight :";
cin>>e[i].wt;
}

bellman_ford(nv,e,src_graph,ne);

return 0;
}

return 0;
}
l O M oA R c P S D | 1 2 2 0 8 0 2 6

OUTPUT:

Enter the number of vertices: 4


Enter the source vertex of the graph: 1

Enter no. of edges: 4

For edge 1=>


Enter source vertex :1
Enter destination vertex :2
Enter weight :4

For edge 2=>


Enter source vertex :1
Enter destination vertex :3
Enter weight :3

For edge 3=>


Enter source vertex :2
Enter destination vertex :4
Enter weight :7

For edge 4=>


Enter source vertex :3
Enter destination vertex :4
Enter weight :-2

Vertex Distance from source


1 0
2 4
3 3
4 1

RESULT:

Thus implementation of shortest path algorithm using C++ Successfully


completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO:11 Implementation of Matrix Chain Multiplication

DATE:

AIM:

Write to implementation of Matrix chain multiplication using C++.

ALGORITHM:

Step 1: Constructing an Optimal Solution:


STEP2: Analysis: There are three nested loops. Each loop executes a maximum n
times.
STEP3: Total Complexity is: O (n3)
STEP4: Question: P [7, 1, 5, 4, 2}
STEP5: Solution: Here, P is the array of a dimension of matrices.

PROGRAM:
#include<iostream>
#include<limits.h>

using namespace std;


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

return m[1][n-1];
l O M oA R c P S D | 1 2 2 0 8 0 2 6

int main()
{
int n,i;
cout<<"Enter number of matrices\n";
cin>>n;

n++;

int arr[n];

cout<<"Enter dimensions \n";

for(i=0;i<n;i++)
{
cout<<"Enter d"<<i<<" :: ";
cin>>arr[i];
}

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

cout<<"Minimum number of multiplications is "<<MatrixChainMultiplication(arr,


size));

return 0;
}

OUTPUT:
Enter number of matrices
4
Enter dimensions
Enter d0 :: 10
Enter d1 :: 100
Enter d2 :: 20
Enter d3 :: 5
Enter d4 :: 80
Minimum number of multiplications is 19000

RESULT:

Thus implementation of Matrix Chain Multiplication using C++ Successfully


completed.
l O M oA R c P S D | 1 2 2 0 8 0 2 6

EX.NO:12 Activity Selection And Huffman Coding Implementation

DATE:

AIM:

Write to implementation of Activity Selection and Huffman coding using


C++.

ALGORITHM:

Step 1: Sort the given activities in ascending order according to their finishing time.

Step 2: Select the first activity from sorted array act[] and add it to sol[] array.

Step 3: Repeat steps 4 and 5 for the remaining activities in act[].

Step 4: If the start time of the currently selected activity is greater than or equal to the
finish time of previously selected activity, then add it to the sol[] array.

Step 5: Select the next activity in act[] array.

Step 6: Print the sol[] array.

PROGRAM:
#include <bits/stdc++.h>

using namespace std;


#define N 6
struct Activity
{
int start, finish;
};

bool Sort_activity(Activity s1, Activity s2)


{
return (s1.finish< s2.finish);
}

void print_Max_Activities(Activity arr[], int n)


{
sort(arr, arr+n, Sort_activity);

cout<< "Following activities are selected \n";

int i = 0;
cout<< "(" <<arr[i].start<< ", " <<arr[i].finish << ")\n";
l O M oA R c P S D | 1 2 2 0 8 0 2 6

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


{
if (arr[j].start>= arr[i].finish)
{
cout<< "(" <<arr[j].start<< ", "<<arr[j].finish << ") \n";i
= j;
}
}
}

int main()
{
Activity arr[N];
for(int i=0; i<=N-1; i++)
{
cout<<"Enter the start and end time of "<<i+1<<" activity \n";
cin>>arr[i].start>>arr[i].finish;
}

print_Max_Activities(arr, N);
return 0;
}

OUTPUT:
Enter the start and end time of 1 activity5
9
Enter the start and end time of 1 activity1
2
Enter the start and end time of 1 activity3
4
Enter the start and end time of 1 activity0
6
Enter the start and end time of 1 activity5
7
Enter the start and end time of 1 activity8
9
Following activity are selected

(1,2)
(3,4)
(5,7)
(8,9)
l O M oA R c P S D | 1 2 2 0 8 0 2 6

RESULT:
Thus implementation of Activity Selection And Huffman Coding using C++
Successfully completed.

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