0% found this document useful (0 votes)
354 views17 pages

Program To Multiply Two Sparse Matrices Using C Language: Course Code:-Mcs 021 Course Name:-Ds Q.1 Ans

The document describes algorithms for performing operations on multiple stacks stored in a single dimensional array. It includes algorithms for push, pop, and displaying stacks for two stacks (A and B) stored in an array. The push and pop algorithms check for overflow and underflow. It also provides an overview of red-black trees, including their properties of being almost balanced binary search trees, with insertions and deletions handled to maintain balance through rotations and recoloring of nodes. Applications of red-black trees include dictionaries, priority queues, set/map implementations, and graph algorithms.

Uploaded by

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

Program To Multiply Two Sparse Matrices Using C Language: Course Code:-Mcs 021 Course Name:-Ds Q.1 Ans

The document describes algorithms for performing operations on multiple stacks stored in a single dimensional array. It includes algorithms for push, pop, and displaying stacks for two stacks (A and B) stored in an array. The push and pop algorithms check for overflow and underflow. It also provides an overview of red-black trees, including their properties of being almost balanced binary search trees, with insertions and deletions handled to maintain balance through rotations and recoloring of nodes. Applications of red-black trees include dictionaries, priority queues, set/map implementations, and graph algorithms.

Uploaded by

Abinash Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COURSE CODE:- MCS 021

COURSE NAME :-DS

Q.1

Ans:-

PROGRAM TO MULTIPLY TWO SPARSE MATRICES USING C LANGUAGE

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define MAX1 3
#define MAX2 3
#define MAXSIZE 20
#define TRUE 1
#define FALSE 2
struct sparse
{
int *sp ;
int row ;
int *result ;
};
void initsparse ( struct sparse * ) ;
void create_array ( struct sparse * ) ;
int count ( struct sparse ) ;
void display ( struct sparse ) ;
void create_tuple ( struct sparse*, struct sparse ) ;
void display_tuple ( struct sparse ) ;
void prodmat ( struct sparse *, struct sparse, struct sparse ) ;
void searchina ( int *sp, int ii, int*p, int*flag ) ;
void searchinb ( int *sp, int jj, int colofa, int*p, int*flag ) ;
void display_result ( struct sparse ) ;
void delsparse ( struct sparse * ) ;
void main( )

1
{
struct sparse s[5] ;
int i ;
clrscr( ) ;
for ( i = 0 ; i<= 3 ; i++ )
initsparse ( &s[i] ) ;
create_array ( &s[0] ) ;
create_tuple ( &s[1], s[0] ) ;
display_tuple ( s[1] ) ;
create_array ( &s[2] ) ;
create_tuple ( &s[3], s[2] ) ;
display_tuple ( s[3] ) ;
prodmat ( &s[4], s[1], s[3] ) ;
printf ( "\nResult of multiplication of two matrices: " ) ;
display_result ( s[4] ) ;
for ( i = 0 ; i<= 3 ; i++ )
delsparse ( &s[i] ) ;
getch( ) ;
}
/* initialises elements of structure */
void initsparse ( struct sparse *p )
{
p -> sp = NULL ;
p -> result = NULL ;
}
/* dynamically creates the matrix */
void create_array ( struct sparse *p )
{
int n, i ;
/* allocate memory */
p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ;
/* add elements to the array */
for ( i = 0 ; i< MAX1 * MAX2 ; i++ )

2
{
printf ( "Enter element no. %d: ", i ) ;
scanf ( "%d", &n ) ;
* ( p -> sp + i ) = n ;
}
}
/* displays the contents of the matrix */
void display ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i< MAX1 * MAX2 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.sp + i ) ) ;
}
}
/* counts the number of non-zero elements */
int count ( struct sparse s )
{
int cnt = 0, i ;
for ( i = 0 ; i< MAX1 * MAX2 ; i++ )
{
if ( * ( s.sp + i ) != 0 )
cnt++ ;
}
return cnt ;
}
/* creates an array that stores information about non-zero elements */
void create_tuple ( struct sparse *p, struct sparse s )
{

3
int r = 0 , c = -1, l = -1, i ;
/* get the total number of non-zero elements */
p -> row = count ( s ) + 1 ;
/* allocate memory */
p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ;
/* store information about total no. of rows, cols, and non-zero values */
* ( p -> sp + 0 ) = MAX1 ;
* ( p -> sp + 1 ) = MAX2 ;
* ( p -> sp + 2 ) = p -> row - 1 ;
l=2;
/* scan the array and store info. about non-zero values in the 3-tuple */
for ( i = 0 ; i< MAX1 * MAX2 ; i++ )
{
c++ ;
/* sets the row and column values */
if ( ( ( i % 3 ) == 0 ) && ( i != 0 ) )
{
r++ ;
c=0;
}
/* checks for non-zero element, row, column and non-zero value is assigned to the matrix
*/
if ( * ( s.sp + i ) != 0 )
{
l++ ;
* ( p -> sp + l ) = r ;
l++ ;
* ( p -> sp + l ) = c ;
l++ ;
* ( p -> sp + l ) = * ( s.sp + i ) ;
}
}
}

4
/* displays the contents of the matrix */
void display_tuple ( struct sparse s )
{
int i, j ;
/* traverses the entire matrix */
printf ( "\nElements in a 3-tuple: " ) ;
j = ( * ( s.sp + 2 ) * 3 ) + 3 ;
for ( i = 0 ; i< j ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.sp + i ) ) ;
}
printf ( "\n" ) ;
}
/* performs multiplication of sparse matrices */
void prodmat ( struct sparse *p, struct sparse a, struct sparse b )
{
int sum, k, position, posi, flaga, flagb, i , j ;
k=1;
p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ;
for ( i = 0 ; i< * ( a.sp + 0 * 3 + 0 ) ; i++ )
{
for ( j = 0 ; j< * ( b.sp + 0 * 3 + 1 ) ; j++ )
{
/* search if an element present at ith row */
searchina ( a.sp, i, &position, &flaga ) ;
if ( flaga == TRUE )
{
sum = 0 ;
/* run loop till there are element at ith row in first 3-tuple */
while ( * ( a.sp + position * 3 + 0 ) == i )

5
{
/* search if an element present at ith col. in second 3-tuple */
searchinb ( b.sp, j, * ( a.sp + position * 3 + 1 ), &posi, &flagb ) ;
/* if found then multiply */
if ( flagb == TRUE )
sum = sum + * ( a.sp + position * 3 + 2 ) * * ( b.sp + posi * 3 + 2 ) ;
position = position + 1 ;
}
/* add result */
if ( sum != 0 )
{
* ( p -> result + k * 3 + 0 ) = i ;
* ( p -> result + k * 3 + 1 ) = j ;
* ( p -> result + k * 3 + 2 ) = sum ;
k=k+1;
}
}
}
}
/* add total no. of rows, cols and non-zero values */
* ( p -> result + 0 * 3 + 0 ) = * ( a.sp + 0 * 3 + 0 ) ;
* ( p -> result + 0 * 3 + 1 ) = * ( b.sp + 0 * 3 + 1 ) ;
* ( p -> result + 0 * 3 + 2 ) = k - 1 ;
}
/* searches if an element present at iith row */
void searchina ( int *sp, int ii, int *p, int *flag )
{
int j ;
*flag = FALSE ;
for ( j = 1 ; j<= * ( sp + 0 * 3 + 2 ) ; j++ )
{
if ( * ( sp + j * 3 + 0 ) == ii )
{

6
*p = j ;
*flag = TRUE ;
return ;
}
}
}
/* searches if an element where col. of first 3-tuple is equal to row of second 3-tuple */
void searchinb ( int *sp, int jj, int colofa, int *p, int *flag )
{
int j ;
*flag = FALSE ;
for ( j = 1 ; j<= * ( sp + 0 * 3 + 2 ) ; j++ )
{
if ( * ( sp + j * 3 + 1 ) == jj && * ( sp + j * 3 + 0 ) == colofa )
{
*p = j ;
*flag = TRUE ;
return ;
}
}
}
/* displays the contents of the matrix */
void display_result ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i< ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.result + i ) ) ;
}

7
}
/* deallocates memory */
void delsparse ( struct sparse *s )
{
if ( s -> sp != NULL )
free ( s -> sp ) ;
if ( s -> result != NULL )
free ( s -> result ) ;
}

Q.2 Implement multiple stack in a signal dimensional array. Write algorithm for various stack operation

Ans:-

#include <STDIO.H>
#define MAX 10

int stack[MAX],topA=-1,topB=MAX;
void pushA(int no)
{
if(topA==topB)
{
printf("\n OVERFLOW");
return;
}
stack[++(topA)]=no;
}
int popA()
{
if(topA==-1)
{
printf("\n UNDERFLOW");
return -999;
}
return stack[(topA)--];
}

void showA()
{
int i;

8
if(topA==-1)
{
printf("\n stack Empty");
return;
}
for(i=topA;i>=0;i--)
{
printf("\n %d",stack[i]);
}
}

void pushB(int no)


{
if(topB-1==topA)
{
printf("\n OVERFLOW");
return;
}
stack[--(topB)]=no;
}

int popB()
{
if(topB==MAX)
{
printf("\n UNDERFLOW");
return -999;
}
return stack[(topB)--];
}

void showB()
{
int i;
if(topB==MAX)
{
printf("\n stack Empty");
return;
}
for(i=topB;i
{
printf("\n %d",stack[i]);
}
}

9
Al;go for push operation

Step 1: If (TOP=n-1) (a) write STACK FULL.


(b)goto step 4.
Step 2: Set TOP<TOP + 1
Step 3: Set S*TOP+<VAL
Step 4: Stop.

Algo for pop operation


if(top==-1)
{
cout<<"\n the stack is empty";
}
else
return arr[top];
top--;
}

Q.4 what are the application of Red- Black tree?

Ans-

Red-black Trees
11.1 Properties
A binary search tree in which
The root is colored black
All the paths from the root to the leaves agree on the number of black nodes
No path from the root to a leaf may contain two consecutive nodes colored red
Empty subtrees of a node are treated as subtrees with roots of black color.
The relation n > 2 - 1 implies the bound h < 2 log (n + 1).
h/2
2

11.2 Insertions
Insert the new node the way it is done in binary search trees
Color the node red
If a discrepancy arises for the red-black tree, fix the tree according to the type of
discrepancy.
A discrepancy can result from a parent and a child both having a red color. The type of
discrepancy is determined by the location of the node with respect to its grand parent, and
the color of the sibling of the parent.
Discrepancies in which the sibling is red, are fixed by changes in color. Discrepancies in
which the siblings are black, are fixed through AVL-like rotations.

10
Changes in color may propagate the problem up toward the root. On the other hand, at
most one rotation is sufficient for fixing a discrepancy.

LLr

if A is the root, then it should be repainted to black

LRr

if A is the root, then it


should be repainted to black

LLb

11
LRb

Discrepancies of type RRr, RLr, RRb, and RLb are handled in a similar manner.
insert 1

insert 2

insert 3

RRb discrepancy

insert 4

RRr discrepancy

insert 5

RRb discrepancy
11.3 Deletions
Delete a key, and a node, the way it is done in binary search trees.

12
A node to be deleted will have at most one child. If the deleted node is red, the tree
is still a red-black tree. If the deleted node has a red child, repaint the child to
black.
If a discrepancy arises for the red-black tree, fix the tree according to the type of
discrepancy. A discrepancy can result only from a loss of a black node.
Let A denote the lowest node with unbalanced subtrees. The type of discrepancy is
determined by the location of the deleted node (Right or Left), the color of the sibling
(black or red), the number of red children in the case of the black siblings, and and the
number of grand-children in the case of red siblings.
In the case of discrepancies which result from the addition of nodes, the correction
mechanism may propagate the color problem (i.e., parent and child painted red) up
toward the root, and stopped on the way by a single rotation. Here, in the case of
discrepancies which result from the deletion of nodes, the discrepancy of a missing black
node may propagate toward the root, and stopped on the way by an application of an
appropriate rotation.

Rb0

change of color, sending the deficiency up to the


root of the subtree

Rb1

13
Rb2

Rr0

might result in LLb discrepancy of parent and


child having both the red color

Rr1

14
Rr2

Applications and related data structures


Redblack trees offer worst-case guarantees for insertion time, deletion time, and search time. Not only
does this make them valuable in time-sensitive applications such as real-time applications, but it makes
them valuable building blocks in other data structures which provide worst-case guarantees; for example,
many data structures used in computational geometry can be based on redblack trees, and
the Completely Fair Scheduler used in current Linux kernels uses redblack trees.
The AVL tree is another structure supporting O(log n) search, insertion, and removal. It is more rigidly
balanced than redblack trees, leading to slower insertion and removal but faster retrieval. This makes it
attractive for data structures that may be built once and loaded without reconstruction, such as language
dictionaries (or program dictionaries, such as the opcodes of an assembler or interpreter).
Redblack trees are also particularly valuable in functional programming, where they are one of the most
common persistent data structures, used to construct associative arrays and sets which can retain

15
previous versions after mutations. The persistent version of redblack trees requires O(log n) space for
each insertion or deletion, in addition to time.
For every 2-4 tree, there are corresponding redblack trees with data elements in the same order. The
insertion and deletion operations on 2-4 trees are also equivalent to color-flipping and rotations in red
black trees. This makes 2-4 trees an important tool for understanding the logic behind redblack trees,
and this is why many introductory algorithm texts introduce 2-4 trees just before redblack trees, even
though 2-4 trees are not often used in practice.

Question 3:
Write a note of not more than 5 pages summarizing the latest research in the area of Shortest Path
Algorithms for graphs. Refer to various journals and other online resources.
Ans:-
SPA

Shortest path problems are among the most fundamental optimization problems with many
applications. The project is devoted to theoretical and experimental study of algorithms for the
shortest path and related problems, including single-source, feasibility, minimum mean cycle,
and point-to-point shortest paths.

Overview
The problem of finding shortest paths in graphs is a fundamental optimization problem with
many applications. The problem has several variants. Algorithms with near-optimal efficiency,
either in theory or in practice, are known for some problem variants, such as the single-source
problem. For other variants, significant improvement over the current state of the art may be
possible.

With the development of geographic information systems (GIS) technology, network and
transportation analyses within a GIS environment have become a common practice in many
application areas. A key problem in network and transportation analyses is the computation of
shortest paths between different locations on a network. Sometimes this computation has to be
done in real time. For the sake of illustration, let us have a look at the case of a 911 call
requesting an ambulance to rush a patient to a hospital. Today it is possible to determine the
fastest route and dispatch an ambulance with the assistance of GIS. Because a link on a real road
network in a city tends to possess different levels of congestion during different time periods of a
day, and because a patient's location can not be expected to be known in advance, it is practically
impossible to determine the fastest route before a 911 call is received. Hence, the fastest route
can only be determined in real time. In some cases the fastest route has to be determined in a
few seconds in order to ensure the safety of a patient. Moreover, when large real road networks
are involved in an application, the determination of shortest paths on a large network can be
computationally very intensive. Because many applications involve real road networks and

16
because the computation of a fastest route (shortest path) requires an answer in real time, a
natural question to ask is: Which shortest path algorithm runs fastest on real road networks?
A network is defined as a directed graph G = (N, A) consisting of a set N of nodes and a set A of arcs with
associated numerical values, such as the number of nodes, n=|N|, the number of arcs, m=|A|, and the
length of an arc connecting nodes i and j, denoted as l(i,j). The shortest path problem can be stated as
follows: given a network, find the shortest distances (least costs) from a source node to all other nodes
or to a subset of nodes on the network. These shortest paths represent a directed tree T rooted from a
source node s with the characteristic that a unique path from s to any node i on the network is the
shortest path to that node (Ahuja et al. 1993). The length of the shortest path from s to any node i is
denoted as d(i). This directed tree is called a shortest path tree. For any network with n nodes, one can
obtain n distinctive shortest path trees. Shortest paths from one (source) node to all other nodes on a
network are normally referred as one-to-all shortest paths. Shortest paths from one source node to a
subset of the nodes on a network can be defined as one-to-some shortest paths. Shortest paths from
every node to every other node on a network are normally called all-to-all shortest paths.

17

You might also like