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

Techno Main Salt Lake

EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Lab Execution Top Sheet for CSE, Sec-B


Student Name : Arvjeet kumar
Roll No : 13000118116
Subject Name : Design and Analysis of Algorithm
Subject Code : PCC-CS-494
Session : 2019 – 2020

CO- Specific Marks Total Remark &


Exp. List of Marks Signature
Date
No. Experiments
CO1 CO2 CO3 CO4 CO5 40

1. Assignment 1 14-02-2020

2. Assignment 2 06-03-2020

3. Assignment 3 20-03-2020

4. Assignment 4 26-03-2020

5. Assignment 5 27-03-2020

6. Assignment 6 03-04-2020

7. Assignment 7 14-04-2020

8. Assignment 8 21-04-2020

9. Assignment 9 28-04-2020

10. Assignment 10 16-05-2020

11. Assignment 11 19-05-2020

12. Assignment 12 26-05-2020

© Department of CSE Page 1 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

NAME OF THE PROGRAM: CSE DEGREE: B. Tech


COURSE NAME: Design & Analysis of Algorithm SEMESTER: 4th
COURSE CODE: PCC-CS494 COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P
SESSION: 2019-2020

Assignment Week
List of Experiments
No. No.
Assignment 1 I) Implement Binary Search using Divide and Conquer approach.
II) Implement Merge Sort, Quick Sort and Heap Sort using Divide and Conquer Week 1
approach.
Assignment 2 I) Find Maximum and Minimum element from a array of integer using Divide
and Conquer approach as well as dynamic programming approach.

II) WAP to multiply two 2x2 matrices using Strassen’s Matrix Multiplication.
The first matrix is
5 6
1 7
The second matrix is
6 2 Week 2
8 7

III) WAP to multiply two 4x4 matrices using Strassen's Matrix Multiplication.

Assignment 3 Find the minimum number of scalar multiplications needed for a chain of
matrices whose sequences are <5, 10, 3, 12, 5, 50, 6> using the dynamic
Week 3
programming technique.

Assignment 4 I) WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘1’, using the Dijkstra’s algorithm, using the
dynamic programming technique.

Week 4

© Department of CSE Page 2 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

II) WAP using the single-source-shortest-path problem to find out the


shortest path from the source vertex ‘s’ using the Bellman-Ford’s algorithm,
using the dynamic programming technique.

Assignment 5 I) WAP to find out the all-pair-shortest-path for the given graph using the
Floyd-Warshall’s algorithm by the dynamic programming technique.

II) WAP using dynamic programming to find the optimal route for the given
graph using TSP and taking vertex ‘1’ as source.
Week 5

Assignment 6 I) WAP to implement BFS on the given graph starting at ‘a’. Week 6

© Department of CSE Page 3 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

II) WAP to implement DFS on the given graph starting at ‘A’.

Assignment 7 I) WAP using greedy method to find the MST for the given graph using the
Prim’s Algorithm.

II) WAP using greedy method to find the MST for the given graph using the Week 7

Kruskal’s Algorithm.

Assignment 8 I) Consider the following knapsack problem where n = 3, W = 20 Kgs, (v1, v2,
Week 8
v3) = (25, 24, 15), and (w1, w2, w3) = (18, 15, 10). WAP to find the optimal

© Department of CSE Page 4 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

solution by fractional knapsack (greedy method) as well as 0 / 1 knapsack


(Dynamic programming method).

II) Given a set of ‘10’ jobs with their si and fi, find the optimal sequence of
mutually compatible jobs using the greedy method: A = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10}, si = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12} and fi = {5, 7, 8, 10, 11, 12, 13, 14, 15,
16}.

Assignment 9 Write a procedure using B & B technique to solve the 15-puzzle problem.
(Take an initial state of your choice that will converge in the goal state.) Week 9

Assignment 10 I) WAP to implement the 4-Queen’s problem using the method of


backtracking.

II) WAP using backtracking to find the chromatic number for the given
graph, using the graph-coloring problem.

Week
10

Assignment 11 The Maximum Sub-array Sum problem is to find the sub-array (A sub-array of
the array A [0…N-1] is A[i…j] where 0 ≤ i ≤ j < N ) for which the sum of its
elements is maximum. For example, given an array {12, -13, -5, 25, -20, 30,
10}, the maximum sub-array sum is 45 for sub-array {25, -20, 30, 10}. The
naive solution to this problem is to calculate the sum of all sub-arrays starting
with every element and returning the maximum of all. WAP to find the
maximum sub-array given below:

(1) Divide the given array in two halves.


Week
(2) Return the maximum of the following: 11
i. Maximum sub-array sum in the left half (Make a

recursive call).

ii. Maximum sub-array sum in the right half (Make

a recursive call).

© Department of CSE Page 5 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Assignment 12 I) Find the only 10 digits number where the digit at the ith position (i = 0,
1, 2, 3 etc.) from left specifies the number of occurrences of digit "i" in
the given number.

II) Find the numbers from 1 to N that contains exactly k non-zero digits

Given two integers N and K. The task is to find the number of integers
between 1 and N (inclusive) that contains exactly K non-zero digits when
written in base ten.

Example: Input: N = 100, K = 1


Output: 19
Week
Explanation:
12
The digits with exactly 1 non zero digits between 1 and 100 are:
1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 20, 30, 40, 50, 60, 70, 80, 90, 100

Input: N = 25, K = 2
Output: 14
Explanation:
The digits with exactly 2 non zero digits between 1 and 25 are:
11, 12, 13, 14, 15, 16, 17,
18, 19, 21, 22, 23, 24, 25

© Department of CSE Page 6 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 1
1.1. Implement Binary Search using Divide and Conquer approach.

Solution: FlowChart

© Department of CSE Page 7 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexty:
For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation
Apply Masters Theorem for computing Run time complexity of recurrence relations
: T(N) = aT(N/b) + f(N)
Here, a = 1, b = 2 => log (a base b) = 1
also, here f(N) = n^c (log^k(n)) // k = 0 & c = log (a base b)
So, T(N) = O(N^c log^(k+1)N) = O(log(N)) // Average and worst case.
Best Case: O(1)

C code:
#include <stdio.h>

void merge(int arr[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
© Department of CSE Page 8 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;

mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}

int binarySearch(int arr[], int l, int r, int x)


{
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}

int main(void)
{
int i,n,temp = 0;
printf("Enter the no. of elements of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
if(arr[i] > arr[i+1])
{

© Department of CSE Page 9 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

temp = 1;
break;
}
}

if(temp == 1)
mergeSort(arr,0,n);

printf("The sorted array is:\n");


for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");

int x;
printf("enter the to be searched:\n");
scanf("%d",&x);

int result = binarySearch(arr,0,n - 1,x);


if(result == -1)
printf("Element is not present in array");
else
printf("Element is present at index %d", result);
printf("\n");
return 0;
}

OUTPUT:
#RUN 1

#RUN 2

© Department of CSE Page 10 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

1.2. Implement Merge Sort, Quick Sort and Heap Sort using Divide and Conquer
approach.

Solution: FlowChart

Merge Sort:

Time Complexity:

Merge Sort is a recursive algorithm and time complexity can be expressed as


following recurrence relation.
T(n) = 2T(n/2) + (n)
The above recurrence can be solved either using Recurrence Tree method or
Master method.
It falls in case II of Master Method and solution of the recurrence is (nLogn).
Time complexity of Merge Sort is (nLogn) in all 3 cases (worst, average and best)
as merge sort always divides the array into two halves and take linear time to
merge two halves.

© Department of CSE Page 11 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

C code:
#include<stdio.h>
#include<stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{

© Department of CSE Page 12 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

if (l < r)
{
int m = l+(r-l)/2;

mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main()
{
int i,n;
printf("Enter the size of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

mergeSort(arr,0,n);

printf("The sorted array is:\n");


for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
OUTPUT:

© Department of CSE Page 13 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Quick Sort:
FlowChart:

© Department of CSE Page 14 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
Time taken by QuickSort in general can be written as following.
T(n) = T(k) + T(n-k-1) + (n)
The first two terms are for two recursive calls, the last term is for the partition
process. k is the number of elements which are smaller than pivot.
The time taken by QuickSort depends upon the input array and partition strategy.
Following are three cases.

Worst Case:
The worst case occurs when the partition process always picks greatest or
smallest element as pivot. If we consider above partition strategy where last
element is always picked as pivot, the worst case would occur when the array is
already sorted in increasing or decreasing order. Following is recurrence for worst
case.
T(n) = T(0) + T(n-1) + (n)
which is equivalent to
T(n) = T(n-1) + (n)
The solution of above recurrence is (n^2).

Best Case:
The best case occurs when the partition process always picks the middle element
as pivot. Following is recurrence for best case.

T(n) = 2T(n/2) + (n)


The solution of above recurrence is (nLogn). It can be solved using case 2 of
Master Theorem.

Average Case:
To do average case analysis, we need to consider all possible permutation of array
and calculate time taken by every permutation which doesn’t look easy.
We can get an idea of average case by considering the case when partition puts
O(n/9) elements in one set and O(9n/10) elements in other set. Following is
recurrence for this case.

T(n) = T(n/9) + T(9n/10) + (n)


Solution of above recurrence is also O(nLogn)

© Department of CSE Page 15 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

C code:
#include<stdio.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int partition(int arr[],int l,int r)


{
int pivot = arr[r],i;
int p_index = l;
for(i=l;i<r;i++)
{
if(arr[i] <= pivot)
{
swap(&arr[i],&arr[p_index]);
p_index++;
}
}
swap(&arr[p_index],&arr[r]);
return(p_index);
}

void quick_sort(int arr[],int l,int r)


{
int j;
if(l < r)
{
j = partition(arr,l,r);
//printf("j = %d",j);
quick_sort(arr,l,j-1);
quick_sort(arr,j+1,r);
}
}

int main()
{
int n;
printf("Enter the size of the Array:\n");
scanf("%d",&n);
int i,arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

© Department of CSE Page 16 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

quick_sort(arr,0,n-1);

for(i=0;i<n;i++)
printf("%d ",arr[i]);
return(0);
}

OUTPUT

© Department of CSE Page 17 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Heap Sort:
Flowchart:

Time Complexity:
Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and
overall time complexity of Heap Sort is O(nLogn).
All three cases have same running time complexity.

© Department of CSE Page 18 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

C code:
#include<stdio.h>
#include<stdlib.h>

void swap(int *x,int *y)


{
int temp = *x;
*x = *y;
*y = temp;
}

void heapify(int arr[], int n, int i)


{
int largest = i;
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2

// If left child is larger


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger


if (r < n && arr[r] > arr[largest])
largest = r;

if (largest != i)
{
swap(&arr[i], &arr[largest]);

// Recursively heapify
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n)


{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i=n-1; i>0; i--)


{
// Move root to end
swap(&arr[0], &arr[i]);

// call heapify
heapify(arr, i, 0);
}

© Department of CSE Page 19 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

void printArray(int arr[], int n)


{
for (int i=0; i<n; ++i)
printf("%d ",arr[i]);
printf("\n");
}

int main()
{

int i,n;
printf("Enter the size of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

heapSort(arr, n);

printf("The sorted array is:: \n");


printArray(arr, n);
}
OUTPUT:

© Department of CSE Page 20 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 2
2.1. Find Maximum and Minimum element from a array of integer using Divide and
Conquer approach as well as dynamic programming approach.

Solution: FlowChart

© Department of CSE Page 21 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 22 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
Form Algo: T(n) = 2.T(n/2) + 2
T(2) = 1
T(1) = 0
So, T(n) = 3*n / 2 – 2 = O(n)
If n is the power of 2, then algo needs O(n) comparisons, if not the comparasions
will be even more.

In D.P.: There will be n comparasions. So, Running time will be O(n)

C code:
#include<stdio.h>
void maximum(int a[],int l,int h,int *min,int *max)
{

if(l==h)
{
if(*max<a[l])
*max=a[l];

if(*min>a[h])
*min=a[h];

return;
}

else if(l+1==h)
{
if(a[l]<a[h])
{
if(*min>a[l])
*min=a[l];

if(*max<a[h])
*max=a[h];
}
else
{
if(*min>a[h])
*min=a[h];
if(*max<a[l])
*max=a[l];
}
return;
}

© Department of CSE Page 23 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int mid=(l+h)/2;
maximum(a,l,mid,min,max);
maximum(a,mid+1,h,min,max);
}

int main()
{
int n,max=-999999,min=999999;
int t=1,x;
while(t)
{

printf("Enter the length of the array : ");


scanf("%d",&n);
int a[n],i;
printf("\nEnter the elements of the array : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("\n1.Divide & conquer\n2.dynimically\n3.Exit\nchoice : ");


scanf("%d",&x);
switch(x)
{
case 1:
maximum(a,0,n-1,&min,&max);
printf("\nMaximum : %d\nMinimum : %d\n",max,min);
break;

case 2:
max=a[0];
min=a[0];
for(i=1;i<n;i++)
{
max=max>a[i]?max:a[i];
min=min<a[i]?min:a[i];
}
printf("\nMaximum = %d\nMinimum = %d\n",max,min);
break;
case 3:
t=0;

}
}

© Department of CSE Page 24 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 25 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

2.2. WAP to multiply two 2x2 matrices using Strassen’s Matrix Multiplication.
The first matrix is
5 6
1 7
The second matrix is
6 2
8 7
Solution: Flowchart

© Department of CSE Page 26 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
As I mentioned above the Strassen’s algorithm is slightly faster than the general
matrix multiplication algorithm. The general algorithm’s time complexity is O(n^3),
while the Strassen’s algorithm is O(n^2.80).

You can see on the chart below how slightly faster is this even for large n.
Explanation:
Addition and Subtraction of two matrices takes O(N2) time. So time complexity can
be written as:
T(N) = 7T(N/2) + O(N^2)
From Master's Theorem, time complexity of above method is
O(N^Log7) which is approximately O(N^2.8074).

C code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[2][2], b[2][2], c[2][2], i, j;
int m1, m2, m3, m4, m5, m6, m7;
printf("Enter the elements of the first matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of the second matrix: \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The first Matrix is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}

© Department of CSE Page 27 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("The second Matrix is: \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}

m1 = (a[0][0] + a[1][1])*(b[0][0] + b[1][1]);


m2 = (a[1][0] + a[1][1])*b[0][0];
m3 = (b[0][1] - b[1][1])*a[0][0];
m4 = a[1][1] * (b[1][0] - b[0][0]);
m5 = (a[0][0] + a[0][1]) * b[1][1];
m6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]);
m7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]);

c[0][0] = m1 + m4 - m5 + m7;
c[0][1] = m3 + m5;
c[1][0] = m2 + m4;
c[1][1] = m1 - m2 + m3 + m6;

printf("The final Matrix is: \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:

© Department of CSE Page 28 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT 3
3. Find the minimum number of scalar multiplications needed for a chain of
matrices whose sequences are <5, 10, 3, 12, 5, 50, 6> using the dynamic
programming technique.

Solution: FlowChart

© Department of CSE Page 29 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

Implementation Rule:
Matrix-Chain(array p[1 .. n], int n) {
Array s[1 .. n − 1, 2 .. n];
FOR i = 1 TO n DO m[i, i] = 0; // initialize
FOR L = 2 TO n DO { // L=length of subchain
FOR i = 1 TO n − L + 1 do {
j = i + L − 1;
m[i, j] = infinity;
FOR k = i TO j − 1 DO { // check all splits
q = m[i, k] + m[k + 1, j] + p[i − 1] p[k] p[j];
IF (q < m[i, j]) {
m[i, j] = q;
s[i, j] = k;
}
}
}
}
return m[1, n](final cost) and s (splitting markers);
}

Form the above Pseudo Code:


Complexity will be –
A simple inspection of the for-loop(s) structures gives us a running time of the
procedure. Since, the three for-loops are nested three deep, and each one of them
iterates at most n times (that is to say indices L, i, and j takes on at most n − 1
values). Therefore, The running time of this procedure is Ο(n^3)
C code:
#include<stdio.h>
#include<stdlib.h>

int MatrixChainMult(int arr[], int n)


{

int A[n][n];

int i, j, k, L, q;
© Department of CSE Page 30 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

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


A[i][i] = 0;

for (L=2; L<n; L++)


{
for (i=1; i<n-L+1; i++)
{
j = i+L-1;
A[i][j] = 999999;
for (k=i; k<=j-1; k++)
{
q = A[i][k] + A[k+1][j] + arr[i-1]*arr[k]*arr[j];
if (q < A[i][j])
A[i][j] = q;
}
}
}
return A[1][n-1];
}

int main()
{
int n,i, result;
printf("Enetr the Size of the array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for ( i = 0; i < n; i++)
scanf("%d",&arr[i]);

result = MatrixChainMult(arr, n);

printf("The minimum number of scalar multiplication needed for chain of matrix\n");


printf("%d",result);
return 0;
}
OUTPUT:

© Department of CSE Page 31 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT 4
4.1. WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘1’, using the Dijkstra’s algorithm, using the dynamic
programming technique.

Solution: FLOWCHART

© Department of CSE Page 32 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 33 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 34 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
This algo. Takes O(n2 ) in both Adj. list and adj Marix.

For the Adj. Matrix:


1. Outer loop runs for ‘n’ Time : O(n)
• In each iteration, visited one vertex and it will take O(n) to scan
minimum weight vertex
• Each time we visited a vertex V, scan all of its neighbour to update
weight.
• O(n) to scan of adj. matrix to find all neighbour
Overall O (n2 ).

C code:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode)


{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;

while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)

© Department of CSE Page 35 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i + 1,distance[i]);
printf("\nPath=%d",i + 1);

j=i;
do
{
j=pred[j];
printf("<-%d",j + 1);
}while(j!=startnode);
}
}

int main()
{
int G[MAX][MAX],i,j,V,u;
printf("Enter no. of vertices:");
scanf("%d",&V);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<V;i++)
for(j=0;j<V;j++)
scanf("%d",&G[i][j]);

© Department of CSE Page 36 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,V,u - 1);

return 0;
}

OUTPUT:

© Department of CSE Page 37 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

4.2. WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘s’ using the Bellman-Ford’s algorithm, using the
dynamic programming technique.

Solution: FlowChart

© Department of CSE Page 38 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 39 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 40 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
Let: |V| = No. of Vertex
|E| = No of Edges

Relaxation will take |V| no. of times over no. of edges


i.e. |E|
therefore, Complexity will be O(|V||E|)
If no. of edges is equal to number of vertex: then O(n2 ).

C code:
#include <stdio.h>
#include <stdlib.h>
#define max 20
#define infinity 9999

typedef struct
{
int e,v,array[max][max];
}graph;

void initialise(graph *g)


{
int i,j,x,y,w;
for(i=1;i<=g->v;i++)
{
for(j=1;j<=g->v;j++)
g->array[i][j]=0;
}
printf("Enter the edges of the graph and their weight : ");
for(i=1;i<=g->e;i++)
{
scanf("%d %d %d",&x,&y,&w);
g->array[x][y]=w;
}
}

int value(graph g, int visited[],int D[])


{
int i;
for(i=1;i<=g.v;i++)
{
if(D[i]!=infinity && visited[i]==0)
return i;
}
}

© Department of CSE Page 41 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

void bellman_ford(graph g,int u)


{
int D[g.v+1],i,j,k,index;
for(i=0;i<=g.v;i++)
D[i]=infinity;
for(k=1;k<g.v;k++)
{
D[u]=0;
int visited[g.v+1];
for(i=1;i<=g.v;i++)
visited[i]=0;
for(i=1;i<=g.v;i++)
{
index=value(g,visited,D);
visited[index]=1;
for(j=1;j<=g.v;j++)
{
if(g.array[i][j]!=0)
{
if(D[j]>D[index]+g.array[index][j])
D[j]=D[index]+g.array[index][j];
}
}
}
}

for(i=1;i<=g.v;i++)
printf("vertex = %d,, Distance = %d \n",i,D[i]);
}

int main()
{
int u;
graph g;
printf("Enter the no. of vertex and edge of graph : ");
scanf("%d %d",&g.v,&g.e);
initialise(&g);
printf("Enter the starting vertex : ");
scanf("%d",&u);
bellman_ford(g,u);
return 0;
}

© Department of CSE Page 42 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 43 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 5
5.1. WAP to find out the all-pair-shortest-path for the given graph using the Floyd-
Warshall’s algorithm by the dynamic programming technique.

Solution: FlowChart

© Department of CSE Page 44 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complxity:

Floyd (adjacency_matrix *g)


{
for (k=1; k<=g->nvertices; k++)
for (i=1; i<=g->nvertices; i++)
for (j=1; j<=g->nvertices; j++) {
through_k = g->weight[i][k] + g->weight[k][j];
if (through_k < g->weight[i][j])
g->weight[i][j] = through_k;
}
}

Form the above Algorithm The Floyd-Warshall all-pairs shortest path runs in O(n3)
time, which is asymptotically no better than n calls to Dijkstra’s algorithm.
However, the loops are so tight and the program so short that it runs better in
practice.

C code:
#include<stdio.h>
#include<stdlib.h>
#define INF 99999
#define max 100

typedef struct Floyd_warshall{


int V;
int E;
int Adj[max][max];
}graph;

void initialise_graph(graph *g)


{
int i,j,u,v,w;
for(i=1;i<=g->V;i++)
{
for(j=1;j<=g->V;j++)
{
if(i==j)
g->Adj[i][j]=0;
else
g->Adj[i][j]=INF;
}
}
printf("Enter the edges of the graph and their weight:\n");

© Department of CSE Page 45 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

for(i=1;i<=g->E;i++)
{
scanf("%d %d %d",&u,&v,&w);
g->Adj[u][v]=w;
}

printf("The initial matrix is:\n");


for(i=1;i<=g->V;i++)
{
for(j=1;j<=g->V;j++)
{
//printf("%d ",g->Adj[i][j]);
if(g->Adj[i][j] == 99999)
{
g->Adj[i][j] = "INF";
printf("INF ");
}
else
printf("%d ",g->Adj[i][j]);

}
printf("\n");
}
printf("\n");
}

int min(int x, int y)


{
if(x < y)
return x;
else
return y;
}

void floyd_warshall(graph g)
{
int i,j,k;
for(k=1;k<=g.V;k++)
{
for(i=1;i<=g.V;i++)
{
for(j=1;j<=g.V;j++)
g.Adj[i][j]=min(g.Adj[i][j],g.Adj[i][k]+g.Adj[k][j]);
}

© Department of CSE Page 46 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("All shortest pair path is:\n");


for(i=1;i<=g.V;i++)
{
for(j=1;j<=g.V;j++)
printf("%d ",g.Adj[i][j]);
printf("\n");
}
}

int main()
{
graph G;
int i,j;
printf("Enter the number of vertices and edges:\n");
scanf("%d %d",&G.V,&G.E);
initialise_graph(&G);
floyd_warshall(G);
return 0;
}
OUTPUT:

© Department of CSE Page 47 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

5.2. WAP using dynamic programming to find the optimal route for the given graph
using TSP and taking vertex ‘1’ as source.

Solution: FlowChart

© Department of CSE Page 48 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 49 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
Recursive definition for travelling salesman problem can be written like this :-
• T(i,S) = min((i,j)+T(j,S-{j})) for all j belonging to S, when S is not equal to
NULL
• T(i,S) = (i,S) when S is equal to NULL.

There are n possible start vertices and 2n possible subgraphs. So this function will
be called on at most n⋅2n distinct arguments (the target never changes). Each call
performs at most O(n) work (there are at most n neighbors). Hence the total work
you're doing is O(n22n).

C code:
#include<stdio.h>
#define V 4

int travelling_sales_problem(int graph[][V],int visited[V])


{
int i,j,ctr =0,cost=0,min,k;
for (k=0;k<V-1;k++)
{
i=ctr;min=999;

for(j=0;j<V;j++)
{

if((graph[i][j]<min)&& (visited[j]==0))
{
min=graph[i][j];
ctr=j;
}

}
visited[ctr]=1;
cost=cost+min;
}
return (cost+graph[ctr][0]);
}

int main()
{
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };

© Department of CSE Page 50 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int visited[]={1,0,0,0};

printf("Given graph in matrix form:\n");


for (int i = 0; i <V; i++)
{
for (int j = 0; j <V; j++)
printf("%d ", graph[i][j]);
printf("\n");
}
printf("\n");

int cost=travelling_sales_problem(graph,visited);

printf("Minimum cost is %d\n ",cost);

return 0;
}
OUTPUT:

© Department of CSE Page 51 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 6
6.1. WAP to implement BFS on the given graph starting at ‘a’.

Solution: FlowChart

© Department of CSE Page 52 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

1. procedure BFS(G, root) is


2 let Q be a queue
3 label root as discovered
4 Q.enqueue(root)
5 while Q is not empty do
6 v := Q.dequeue()
7 if v is the goal then
8 return v
9 for all edges from v to w in G.adjacentEdges(v) do
10 if w is not labeled as discovered then
11 label w as discovered
12 w.parent := v
13 Q.enqueue(w)

Performing an O(1) operation L times, results to O(L) complexity. Thus, removing


and adding a vertex from/to the Queue is O(1), but when you do that for V vertices,
you get O(V) complexity. Therefore, O(V) + O(E) = O(V+E)

C code:
#include <stdio.h>
#include <stdlib.h>
#define err_code -999
#define max 20

typedef struct
{
int edge;
int vertex;
int Adj[20][20];
}graph;

typedef struct queue


{
int cap,*array,front,rear;
}queue;

void initialise(queue *q,int num)


{
q->cap=num;
q->front=-1;
q->rear=-1;
© Department of CSE Page 53 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

q->array=(int *)malloc(sizeof(int)*num);
}

int is_full(queue q)
{
return((q.rear+1)%q.cap==q.front);
}

int is_empty(queue q)
{
return(q.front==-1);
}

void Enqueue(queue *q,int data)


{
if(is_full(*q))
{
printf("Queue is full\n");
return;
}
q->rear=(q->rear+1)%q->cap;
q->array[q->rear]=data;
if(q->front==-1)
{
q->front=q->rear;
}

int Dequeue(queue *q)


{
if(is_empty(*q))
{
printf("Queue is empty\\n");
return err_code;
}
int data;
data=q->array[q->front];
if(q->front==q->rear)
{
q->front=-1;
q->rear=-1;
}
else
q->front=(q->front+1)%q->cap;
return data;
}

© Department of CSE Page 54 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int queue_size(queue q)
{
int data;
data=(q.cap-q.front+q.rear+1)%q.cap;
if(data==0)
return q.cap;
return data;
}

void initialise_graph(graph *g,int V,int e)


{
printf("\nReading edges:\n");
int i,j;
char s, u, p, v;
for(i=1;i<=V;i++)
{
for(j=1;j<=V;j++)
g->Adj[i][j]=0;
}

for(i=0;i<e;i++)
{
scanf("%c%c%c%c",&s,&u,&p,&v);
//printf("u=%d and v=%d",u-96,v-96);
g->Adj[u-96][v-96]=1;
g->Adj[v-96][u-96] = 1;
}
}

void bfs(graph *g,int s,int V)


{
queue q;
initialise(&q,max);
Enqueue(&q,s);
int visited[20]={0},i,j;
printf("%c ",s + 96);
visited[s]=1;
while(!is_empty(q))
{
i=Dequeue(&q);
for(j=1;j<=V;j++)
{
if(g->Adj[i][j]==1&&visited[j]==0)
{
printf("%c ",j + 96);

© Department of CSE Page 55 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Enqueue(&q,j);
visited[j]=1;
}
}
}
}
int main()
{
int e,v;
char ch;
graph g;
printf("enter the number of vertices and the edges of graph : ");
scanf("%d %d",&v,&e);
printf("**All the inputs must be in lower case**\n");
initialise_graph(&g,v,e);
printf("\n");
printf("Enter the starting vertex:\n");
fflush(stdin);
scanf("%c",&ch);
int t = ch - 96;
bfs(&g,t,v);

}
OUTPUT:

© Department of CSE Page 56 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

6.2. WAP to implement DFS on the given graph starting at ‘A’.

Solution: FlowChart

© Department of CSE Page 57 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

A recursive implementation of DFS:


procedure DFS(G, v) is
label v as discovered
for all directed edges from v to w that are in G.adjacentEdges(v) do
if vertex w is not labeled as discovered then
recursively call DFS(G, w)

The time complexity of DFS if the entire tree is traversed is O(V)O(V) where V is the
number of nodes. In the case of a graph, the time complexity is O(V + E)O(V+E)
where V is the number of vertexes and E is the number of edges.

C code:

#include<stdio.h>
#include<stdlib.h>

typedef struct graph


{
int V;
int E;
int **Adj; //2D array
}graph;

void print_DFS(int** edges, int n, int sv, int* visited)


{
int i;
if(sv == 0)
printf("A ");
else if(sv == 1)
printf("B ");
else if(sv == 2)
printf("C ");
else if(sv == 3)
printf("D ");
else
printf("E ");
//printf("%d ", sv);
visited[sv] = 1;
for(i = 0;i<n;i++){
if(i == sv)
continue;
if(edges[sv][i] == 1){
if(visited[i]){
© Department of CSE Page 58 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

continue;
}
print_DFS(edges, n, i, visited);
}
}
}

graph *adj_mat(){
int i, u, v, sv;
char ch;
int* visited;
graph *G = (graph *)malloc(sizeof(graph));
printf("Enter the number of vertex and edge:\n");
scanf("%d %d",&G->V,&G->E);
G->Adj = (int **)malloc(sizeof(int) * (G->V ));
if(!(G->Adj))
{
printf("memory error\n");
return;
}

for(i = 0;i<G->V; i++)


G->Adj[i] = (int *)malloc(sizeof(int) * (G->V));

for(u = 0;u < G->V; u++)


{
for(v = 0;v < G->V; v++)
{
G->Adj[u][v] = 0;
}
}
printf("Reading Edge: \n");
for(i = 0; i < G->E ;i++){
scanf("%d %d",&u,&v);
G->Adj[u][v] = 1;
G->Adj[v][u] = 1;
}
visited = (int *)malloc(sizeof(int) * G->V);
for(i = 0;i<G->V;i++)
{
visited[i] = 0;
}
printf("Enter the starting vertex:\n");
scanf("%s", &ch);
if (ch == 'A')
sv = 0;
print_DFS(G->Adj, G->V, sv, visited);

© Department of CSE Page 59 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("\n");
return(G);
}

int main(){
graph *g;
int i,j;
g = (graph *)malloc(sizeof(graph));
g = adj_mat();
printf("\n\n");
printf("Crossponding Adj. Matrix:\n");
for(i = 0;i<g->V;i++)
{
for(j = 0;j<g->V;j++)
{
printf("%d ",g->Adj[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:

© Department of CSE Page 60 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNEMNT – 7
7.1. WAP using greedy method to find the MST for the given graph using the Prim’s
Algorithm.

Solution: Flowchart

© Department of CSE Page 61 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
Extracting the minimum and tracking the updated minimum edges (usually done
with a Heap(priority Queue), resulting in log(V) time complexity) occurs inside the
loop iterations
• the exact mechanisms involve end up needing to occur inside the inner loop
enough times that they are controlled by the time complexity of both loops.
Therefore, the complete time complexity for this phase of the algorithm is
O(2*E*log(V)). Dropping the constant yields O(E*log(V)).
C code:
#include <stdio.h>
#include <stdlib.h>
#define INF 999999

int minKey(int key[], int mstSet[], int V) {


int min = INF, min_index, v;
for (v = 0; v < V; v++)
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}

int printMSTree(int parent[], int **graph, int V) {


int cost = 0, i;
printf("Edge \tWeight\n");
for (i = 1; i < V; i++) {
printf("%d %d \t%d\n", parent[i], i, graph[i][parent[i]]);
cost += graph[i][parent[i]];
}
printf("Cost: %d.\n", cost);
}

void primMST(int **graph, int V) {


int parent[V];
int key[V];
int mstSet[V];
int i, count, u, v;
for (i = 0; i < V; i++)
key[i] = INF, mstSet[i] = 0;
key[0] = 0;
parent[0] = -1;
for (count = 0; count < V - 1; count++) {
u = minKey(key, mstSet,V);
mstSet[u] = 1;
© Department of CSE Page 62 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

for (v = 0; v < V; v++)


if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

printMSTree(parent, graph, V);


}

int setAdgecencyMatrix(int** adj, int edges, int vertices){


int i, j, x , y, w;
for (i = 0; i < edges; i++) {
scanf("%d %d %d", &x, &y, &w);
adj[x-1][y-1] = w;
adj[y-1][x-1] = w;
}
return 0;
}

int printAdjacencyMatrix(int **adj, int V){


int i, j;
printf("Adjacency Matrix:\n");
for(i = 0; i < V; i++){
for(j = 0; j < V; j++){
if(adj[i][j]==INF)
printf("INF ");
else
printf("%3d ", adj[i][j]);
}
printf("\n");
}
}
int main()
{
int **adj,i,j,v ,e, bi;
printf("Number of vertices: ");
scanf("%d",&v);
adj = (int **)malloc(sizeof(int*)*v);
for(i = 0; i < v; i++){
adj[i] = (int *)malloc(sizeof(int)*v);
for(j = 0; j < v; j++){
if(i==j)
adj[i][j] = 0;
else
adj[i][j] = INF;
}
}
printf("Number of edges: ");

© Department of CSE Page 63 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

scanf("%d",&e);
printf("Enter 2 vertices and correspoding weight for each edge:\n");
setAdgecencyMatrix(adj, e ,v);
printAdjacencyMatrix(adj, v);
primMST(adj, v);
return 0;
}

OUTPUT:

© Department of CSE Page 64 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

7.2. WAP using greedy method to find the MST for the given graph using the
Kruskal’s Algorithm.

Solution: FlowChart

© Department of CSE Page 65 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

algorithm Kruskal(G) is
A := ∅
for each v ∈ G.V do
MAKE-SET(v)
for each (u, v) in G.E ordered by weight(u, v), increasing do
if FIND-SET(u) ≠ FIND-SET(v) then
A := A ∪ {(u, v)}
UNION(FIND-SET(u), FIND-SET(v))
return A

O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time.


After sorting, we iterate through all edges and apply find-union algorithm.
The find and union operations can take atmost O(LogV) time.
So overall complexity is O(ELogE + ELogV) time.
The value of E can be atmost O(V2), so O(LogV) are O(LogE) same.
Therefore, overall time complexity is O(ElogE) or O(ElogV)

C code:

#include<stdio.h>
#include<stdlib.h>

typedef struct MST{


int source;
int dest;
int weight;
}tree;

void bsort(tree *edge, int E)


{
int i, j;
tree temp;

for (i = 0; i < E - 1; i++)


{
for (j = 0; j < (E - 1 - i); j++)
{
if (edge[j].weight > edge[j + 1].weight)
{
temp = edge[j];
edge[j] = edge[j + 1];
edge[j + 1] = temp;

© Department of CSE Page 66 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
}
}

int find_parent(int n, int *parent)


{
if(parent[n] == n){
return n;
}

return find_parent(parent[n], parent);


}
void Kruskals(tree *E, int edge, int vertex)
{
//sort the array according to weight
bsort(E, edge);
tree output_edge[vertex - 1];
//printf("2\n");
int parent[vertex], i;
for(i = 0; i < vertex; i++){
parent[i] = i;
}

int ctr = 0, j = 0;
tree cur_edge;
while (ctr != vertex - 1){
cur_edge = E[j];
//check if to add current edge in the output array is safe or not
int source_parent = find_parent(cur_edge.source, parent);
int dest_parent = find_parent(cur_edge.dest, parent);

if(source_parent != dest_parent){
output_edge[ctr] = cur_edge;
ctr++;
parent[source_parent] = dest_parent;
}
j++;
}

printf("\n");

printf("The final array for the MST is:\n");


for(i = 0; i < vertex-1; i++){
if(output_edge[i].source < output_edge[i].dest){
printf("%d-->%d : %d", output_edge[i].source, output_edge[i].dest, output_edge[i].weight);

© Department of CSE Page 67 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("\n");
}
else
{
printf("%d-->%d : %d", output_edge[i].dest, output_edge[i].source, output_edge[i].weight);
printf("\n");
}
}
int sum = 0;
printf("The total cost is: ");
for(i = 0; i < vertex - 1 ; i++){
sum = sum + output_edge[i].weight;
}
printf("%d", sum);
}

int main()
{
int E, V;
printf("Enter the Number of Vertices and Edges:\n");
scanf("%d %d", &V, &E);
tree Edge[E];
int i, s, d, w;
printf("Enter the Source Vertix, Destination Vertex and Weight:\n");
for(i = 0; i< E; i++){
scanf("%d%d%d", &s, &d, &w);
Edge[i].source = s;
Edge[i].dest = d;
Edge[i].weight = w;
}
//printf("1\n");
Kruskals(Edge, E, V);
return 0;
}

© Department of CSE Page 68 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 69 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNEMENT – 8
8.1. Consider the following Knapsack problem where n = 3, W = 20 Kgs, (v1, v2, v3) =
(25, 24, 15), and (w1, w2, w3) = (18, 15, 10). WAP to find the optimal solution by
fractional knapsack (greedy method) as well as 0 / 1 knapsack (Dynamic
programming method).
Solution: FlowChart

© Department of CSE Page 70 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
In the fractional Knapsack problem: Main time is taking in sorting of the array, So
complexity depend on the type of sorting algorithm.
In case of Quick Sort: Best case O(n*log(n))
Worst case O(n2)
Average case O(n*log(n))

In 0/1 Knapsack Problem: Here the maximum of the empty set is taken to be zero.
Tabulating the results from m[0] up through m[W] gives the solution. Since the
calculation of each m[w] involves examining at most n items, and there are at most
W values of m[w] to calculate, the running time of the dynamic programming
solution is O(n*W).

C Code:
#include<stdio.h>
#include<stdlib.h>

typedef struct Knapsack_greedy


{
int profit;
int weight;
float probywgt;
}sack1;
typedef struct Knapsack_DP
{
int profit;
int value;
}sack2;
int max(int a, int b)
{
return (a > b) ? a : b ;
}
int knapsack_DP(sack2 *A, int n, int max_weight)
{
int i, j;
int dp[n + 1][max_weight + 1];
for (i = 0; i <= n; i++){
for(j = 0; j <= max_weight; j++){
if(i == 0 || j == 0)
dp[i][j] = 0;
else if(A[i].value <= j)
dp[i][j] = max(A[i - 1].profit + dp[i - 1][j - (A[i - 1].value)], dp[i -1][j]);
else
dp[i][j] = dp[i - 1][j];

© Department of CSE Page 71 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
}

return dp[n][max_weight];
}

void bsort(sack1 *A, int n)


{
int i, j;
sack1 temp;
for (i = 0; i < n - 1; i++){
for (j = 0; j < (n - 1 - i); j++){
if (A[j].probywgt < A[j + 1].probywgt){
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}

}
double knapsack_greedy(sack1 *A, int n, int max_weight)
{
bsort(A, n);
int cur_weight = 0, i, reminder = 0;
double result = 0;
for(i = 0; i < n; i++){
if(cur_weight + A[i].weight <= max_weight){
cur_weight = cur_weight + A[i].weight;
result = result + A[i].profit;
}

else{
reminder = max_weight - cur_weight;
result = result + (A[i].profit * ((1.0) * reminder / A[i].weight));
break;
}
}
return result;
}

int main()
{
int swt;
printf("Enter 1 for greedy approach and 2 for DP approach for filling the sack:\n");
scanf("%d",&swt);
if(swt == 1){

© Department of CSE Page 72 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int n, max_weight;
int p, w;
printf("Enter the number of objects and maximum weight that can be filled in the
sack:\n");
scanf("%d %d",&n, &max_weight);
int i;
sack1 A[n];
printf("Enter the profit value and wight value of the object:\n");
for(i = 0; i < n; i++){
scanf("%d %d",&p, &w);
A[i].profit = p;
A[i].weight = w;
A[i].probywgt = ((double)p / w);
}
double result;
result = knapsack_greedy(A, n, max_weight);
printf("The maximum profit by the given capacity of the sack is:\n");
printf("%lf", result);
}
else if(swt == 2){
int n, max_weight;
printf("Enter the number of objects and the maximum capacity of the sack:\n");
scanf("%d %d", &n, &max_weight);
sack2 A[n];
int i;
printf("Enter the profit and weight of the objects:\n");
for(i = 0; i < n; i++)
scanf("%d %d", &A[i].profit, &A[i].value);

int result;
result = knapsack_DP(A, n, max_weight);
printf("The maximum profit by the given capacity of the sack is:\n");
printf("%d", result);
}
else{
printf("Invalid input\n");
}
return 0;
}

© Department of CSE Page 73 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 74 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

8.2. Given a set of ‘10’ jobs with their si and fi, find the optimal sequence of mutually
compatible jobs using the greedy method: A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, si = {3, 4, 5,
6, 7, 8, 9, 10, 11, 12} and fi = {5, 7, 8, 10, 11, 12, 13, 14, 15, 16}.

Solution: Flowchart

© Department of CSE Page 75 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
When activities are sorted by their finish time: O(N)
When activities are not sorted by their finish time, the time complexity is O(N log N)
due to complexity of sorting.

C code:
#include<stdio.h>
#include<stdlib.h>

typedef struct Activity_greedy


{
int start;
int finish;
}act;

void bsort(act *A, int n)


{
int i, j;
act temp;
for (i = 0; i < n - 1; i++){
for (j = 0; j < (n - 1 - i); j++){
if (A[j].finish > A[j + 1].finish){
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}

void Activity(act *A, int n)


{
int output[n], i, j;
for(i = 0; i< n; i++)
output[i] = 0;
bsort(A, n);
printf("The sequence of mutually compatible jobs is:\n");
printf("%d --> %d", A[0].start, A[0].finish);
i = 0;
for(j = 1; j < n; j++){
if(A[j].start >= A[i].finish)
{
output[j] = j;
i = j;
}
}
© Department of CSE Page 76 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int ctr = 1;
printf("\n");
for(i = 1; i < n ; i ++){
if(output[i] != 0){
printf("%d --> %d", A[i].start, A[i].finish);
printf("\n");
ctr++;
}
}
printf("Total number of activity is: %d", ctr);
}

int main()
{
int n, i;
printf("Enter the number of activity a person want to perform:\n");
scanf("%d",&n);
act A[n];
printf("Enter the starting time and finishing time:\n");
for(i = 0; i< n; i++)
scanf("%d %d", &A[i].start, &A[i].finish);
Activity(A, n);
}

OUTPUT:

© Department of CSE Page 77 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 9
9. Write a procedure using B & B technique to solve the 15-puzzle problem. (Take
an initial state of your choice that will converge in the goal state.)

Solution: FlowChart

© Department of CSE Page 78 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
The time complexity of the algo. basically, depends on exploring a live node,
computing cost of construction for each child, finding next E-node. Since, the Algo
is based on B-search. B-search always finds a goal state nearest to root node.
Whatever may be the initial arrangement, the algo always attempts to make the
same sequence of legal moves. The B-search always generate state space tree
level wise. Therefore, the time complexity of this Algo. i.e. => O(|V| + |E|).

C Code:
#include<stdio.h>
#include<conio.h>

int m=0,n=4;

int cal(int temp[10][10],int t[10][10])


{
int i,j,m=0;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
if(temp[i][j]!=t[i][j])
m++;
}
return m;
}

int check(int a[10][10],int t[10][10])


{
int i,j,f=1;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
if(a[i][j]!=t[i][j])
f=0;
return f;
}

void main()
{
int p,i,j,n=4,a[10][10],t[10][10],temp[10][10],r[10][10];
int m=0,x=0,y=0,d=1000,dmin=0,l=0;
printf("\nEnter the matrix to be solved,space with zero :\n");
for(i=0;i < n;i++)
for(j=0;j < n;j++)

© Department of CSE Page 79 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

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

printf("\nEnter the target matrix,space with zero :\n");


for(i=0;i < n;i++)
for(j=0;j < n;j++)
scanf("%d",&t[i][j]);

printf("\nEntered Matrix is :\n");


for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}

printf("\nTarget Matrix is :\n");


for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",t[i][j]);
printf("\n");
}

while(!(check(a,t)))
{
l++;
d=1000;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
if(a[i][j]==0)
{
x=i;
y=j;
}
}

//To move upwards


for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];

if(x!=0)
{
p=temp[x][y];
temp[x][y]=temp[x-1][y];
temp[x-1][y]=p;

© Department of CSE Page 80 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}

//To move downwards


for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(x!=n-1)
{
p=temp[x][y];
temp[x][y]=temp[x+1][y];
temp[x+1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}

//To move right side


for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(y!=n-1)
{
p=temp[x][y];
temp[x][y]=temp[x][y+1];
temp[x][y+1]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)

© Department of CSE Page 81 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

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


r[i][j]=temp[i][j];
}

//To move left


for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(y!=0)
{
p=temp[x][y];
temp[x][y]=temp[x][y-1];
temp[x][y-1]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}

printf("\nCalculated Intermediate Matrix Value :\n");


for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",r[i][j]);
printf("\n");
}
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
a[i][j]=r[i][j];
temp[i][j]=0;
}
printf("Minimum cost : %d\n",d);
}
getch();
}

© Department of CSE Page 82 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 83 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 10
10.1. WAP to implement the 8-Queen’s problem using the method of backtracking.

Solution: Flowchart

© Department of CSE Page 84 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
In the function: is_safe, it iterates over n => O(n2)

In function solve N-queen: In each iteration, there is call of is safe function which of
given order and a recursive call with smaller argument is done:
Therefore, T(n) = n.T(n – 1) + O(n2)

This recursive case will give:


T(n) = O(n!)
And in worst case T(n) = O(n n)

C code:
#include<stdio.h>

#include<stdlib.h>

#define true 1

#define false 0

typedef struct Nqueen

int n;

int **board;

}queen;

int isSafeToPlace(queen *a, int start, int i)

//Checking for row

int r;

for(r = 0; r < start; r++){

if(a->board[r][i] == 1){

return false;

//Checking for left and right digonals

© Department of CSE Page 85 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int digL, digR;

digL = start;

digR = i;

while (digL >= 0 && digR >= 0){

if(a->board[digL][digR] == 1){

return false;

digR--;

digL--;

digL = start;

digR = i;

while (digL >= 0 && digR < a->n){

if(a->board[digL][digR] == 1){

return false;

digR++;

digL--;

//If safe return true

return true;

int solveNqueen(queen *a, int start)

//base case

if(a->n == start){

//print board

int x, y;

© Department of CSE Page 86 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

printf("+-");

for(x = 0; x < 2 * a->n; x++)

printf("-");

printf("+");

printf("\n");

for(x = 0; x < a->n; x++){

printf("| ");

for(y = 0; y < a->n; y++){

if(a->board[x][y] == 1){

printf("Q ");

else{

printf(". ");

printf("|");

printf("\n");

printf("+-");

for(x = 0; x < 2 * a->n; x++)

printf("-");

printf("+");

printf("\n\n");

return false;

//recursive call under which backtracking will be operated

int i;

for(i = 0; i < a->n; i++){

© Department of CSE Page 87 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

if(isSafeToPlace(a, start, i)){

a->board[start][i] = 1;

int placeNext;

placeNext = solveNqueen(a, start + 1);

if(placeNext){

return true;

//if placenext is false then position is wrong

a->board[start][i] = 0;

return false;

int main()

queen *a = (queen *)malloc(sizeof(queen));

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

scanf("%d",&a->n);

int i, j;

a->board = (int **)malloc(sizeof(int) * (a->n));

for(i = 0; i< a->n; i++)

a->board[i] = (int *)malloc(sizeof(int) * (a->n));

solveNqueen(a, 0);

return 0;

© Department of CSE Page 88 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 89 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

10.2. WAP using backtracking to find the chromatic number for the given graph, using the graph-

coloring problem.
Solution:
FlowChart

© Department of CSE Page 90 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

Time Complexity will depend on no. of colors(c) and vertices(v). Total possible
arrangements for
C colours and v vertices is Cn
So running time will be O(Cn).

C code:
#include<stdio.h>
#include<stdlib.h>

typedef struct graph


{
int V;
int E;
int m;
int **Adj; //2D array
int *color;
}graph;
graph *adj_mat(){
int i, u, v, sv;
char ch;
int* visited;
graph *G = (graph *)malloc(sizeof(graph));

printf("Enter the number of vertex and edge::\n");


scanf("%d %d",&G->V,&G->E);

G->Adj = (int **)malloc(sizeof(int) * (G->V ));

if(!(G->Adj)){
printf("memory error\n");
return 0;
}
for(i = 0;i<G->V; i++)
G->Adj[i] = (int *)malloc(sizeof(int) * (G->V));

for(u = 0;u < G->V; u++){


for(v = 0;v < G->V; v++){
G->Adj[u][v] = 0;
}
}
printf("Reading Edge:: \n");
for(i = 0; i < G->E ;i++){
scanf("%d %d",&u,&v);
G->Adj[u][v] = 1;
G->Adj[v][u] = 1;
© Department of CSE Page 91 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
return(G);
}
int checkForValidation(graph *g)
{
int i,j;
for(i = 0; i < g->V; i++){
for(j = i + 1; j < g->V; j++){
if(g->Adj[i][j] == 1 && g->color[j] == g->color[i])
return 0;
}
}
return 1;
}
int graphColoring(graph *g, int start)
{
if(start == g->V){
if(checkForValidation(g)){
int i;
printf("Solution for the given graph is::\n");
for(i = 0; i < g->V; i++){
printf("Vertex::%d --> ",i + 1);
printf("%d",g->color[i]);
printf("\n");
}
return 1;
}
return 0;
}
int i;
for(i = 1; i <= g->m; i++){
g->color[start] = i;
if(graphColoring(g, start + 1)){
return 1;
}
g->color[start] = 0;
}
return 0;
}
int main(){
graph *g;
int i,j;

g = (graph *)malloc(sizeof(graph));
g = adj_mat();
g->color = (int *)malloc(sizeof(int) * g->V);
for(i = 0; i < g->V; i++)

© Department of CSE Page 92 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

g->color[i] = 0;

printf("\n\n");

printf("Crossponding Adj. Matrix::\n");


for(i = 0;i<g->V;i++){
for(j = 0;j<g->V;j++){
printf("%d ",g->Adj[i][j]);
}
printf("\n");
}

printf("Enter the number of color:: ");


scanf("%d",&g->m);

int start;
printf("Enetr the starting vertex:: ");
scanf("%d",&start);
graphColoring(g, start - 1);
return 0;
}
OUTPUT:

© Department of CSE Page 93 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 11
11. The Maximum Sub-array Sum problem is to find the sub-array (A sub-array of
the array A [0…N-1] is A[i…j] where 0 ≤ i ≤ j < N ) for which the sum of its elements is
maximum. For example, given an array {12, -13, -5, 25, -20, 30, 10}, the maximum
sub-array sum is 45 for sub-array {25, -20, 30, 10}. The naive solution to this
problem is to calculate the sum of all sub-arrays starting with every element and
returning the maximum of all. WAP to find the maximum sub-array given below:
(1) Divide the given array in two halves.
(2) Return the maximum of the following:
i. Maximum sub-array sum in the left half (Make a
recursive call).
ii. Maximum sub-array sum in the right half (Make
a recursive call).

Solution: Flowchart

© Department of CSE Page 94 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

© Department of CSE Page 95 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:
maxSubArraySum() is a recursive method and time complexity can be expressed
as following recurrence relation.
T(n) = 2T(n/2) + Θ(n)
The above recurrence is similar to Merge Sort and can be solved either using
Recurrence Tree method or Master method. It falls in case II of Master Method and
solution of the recurrence is Θ(nLogn).

C code:
#include<stdio.h>
#include<stdlib.h>

//Returns the max value


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

//Recursive function to get the max Subarray


int solve(int arr[], int n)
{
if(n == 1) //Base Case
return arr[0];

//All the recursive call over the left half


// and right half
int mid = n / 2; //Middle point
int left_MSS, right_MSS; //MSS = MAximum Sum Subarray

/* Return maximum of following three possible cases


a) Maximum subarray sum in left half
b) Maximum subarray sum in right half */

left_MSS = solve(arr, mid); //made a recursive call


right_MSS = solve(arr + mid, n - mid); //made a recursive call

//
int left_rec = INT_MIN, right_rec = INT_MIN, sum = 0, i;

// for the elements on the left side of the mid


for(i = mid; i < n; i++){
sum += (arr[i]);
right_rec = max(right_rec, sum);
}

© Department of CSE Page 96 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

// for the elements on the right side of the mid


sum = 0;
for(i = (mid - 1); i >= 0; i--){
sum += (arr[i]);
left_rec = max(left_rec, sum);
}

//We will get the maximum of the left or right Sum Subarray
int maxSum = max(left_MSS, right_MSS);

//return the maximum of the left or right or best subarray throught the middle
return(max(maxSum, left_rec + right_rec));
}

int main()
{
int n;
printf("Array Size:\n");
scanf("%d",&n);
int arr[n];
printf("Enter array values:\n");
int i, a;
for(i = 0; i < n; i++){
scanf("%d",&a);
arr[i] = a;
}
int result = solve(arr, n);
printf("Maximum Sub_Array Sum is: %d\n",result);
return 0;
}
OUTPUT:

© Department of CSE Page 97 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

ASSIGNMENT – 12
12.1. Find the only 10 digit number where the digit at the ith position (i = 0, 1, 2, 3 etc.)
from left specifies the number of occurrences of digit "i" in the given number.

Solution: FlowChart

© Department of CSE Page 98 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

Form the code, it is clear that, running time is: O(n)

In the last else:


A while loop run for: n -7 times.
A for loop will run for 3 times to append ‘1000’.

T(n) = O(n – 1) + O(3) + c


Overall O(n).

C code:
#include<stdio.h>
#include<stdlib.h>

void solve(int n)
{
if(n == 1 || n == 2 || n == 3 || n == 6){
printf("No such number exists for %d digit number\n", n);
return;
}
else if(n == 4){
printf("The required number is: 1210 or 2020");
return;
}
else if(n == 5){
printf("The required number is: 21200");
}
else{
int arr[n];
arr[0] = n - 4;
arr[1] = 2;
arr[2] = 1;
int i = n - 7;
int x = 3;
while(i > 0){
arr[x] = 0;
i -= 1;
x += 1;
}
for(i = n - 1; i >= n - 4; i--){
arr[i] = 0;
if(i == n - 4)
arr[i] = 1;

© Department of CSE Page 99 of 110


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

}
printf("The required number is:\n");
for(i = 0; i < n; i++){
printf("%d",arr[i]);
}
return;
}
}

int main()
{
int num;
printf("Enter the number of digits:\n");
scanf("%d",&num);
solve(num);
return 0;
}

OUTPUT:

© Department of CSE Page 100 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

12.2. From this graph find the MST by using 1> Prims Algorithm 2>Kruskal's Algorithm.

Prim’s Algorithm
Solution: Flowchart

© Department of CSE Page 101 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

Extracting the minimum and tracking the updated minimum edges (usually done with a Heap(priority Queue),
resulting in log(V) time complexity) occurs inside the loop iterations
the exact mechanisms involve end up needing to occur inside the inner loop enough times that they are
controlled by the time complexity of both loops. Therefore, the complete time complexity for this phase of the
algorithm is O(2*E*log(V)). Dropping the constant yields O(E*log(V)).

C code:
#include <stdio.h>
#include <stdlib.h>
#define INFINITY 999999
int minKey(int key[], int mstSet[], int V) {
int min = INFINITY, min_index, v;
for (v = 0; v < V; v++)
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
int printMST(int parent[], int **graph, int V) {
int cost = 0, i;
printf("Edge \tWeight\n");
for (i = 1; i < V; i++) {
printf("%d--%d \t%d\n", parent[i], i, graph[i][parent[i]]);
cost += graph[i][parent[i]];
}
printf("Cost: %d.\n", cost);
}
void primMST(int **graph, int V) {
int parent[V];
int key[V];
int mstSet[V];
int i, count, u, v;
for (i = 0; i < V; i++)
key[i] = INFINITY, mstSet[i] = 0;

key[0] = 0;
parent[0] = -1;
for (count = 0; count < V - 1; count++) {
u = minKey(key, mstSet,V);
mstSet[u] = 1;
for (v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph, V);
}
© Department of CSE Page 102 of
110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

int setAdgecencyMatrix(int** adj, int edges, int vertices, int isBiDirectional){


int i, j, x , y, w;
for (i = 0; i < edges; i++) {
scanf("%d %d %d", &x, &y, &w);
adj[x-1][y-1] = w;
if(isBiDirectional)
adj[y-1][x-1] = w;
}
return 0;
}

int printAdjacencyMatrix(int **adj, int V){


int i, j;
printf("Adjacency Matrix:\n");
for(i = 0; i < V; i++){
for(j = 0; j < V; j++){
if(adj[i][j]==INFINITY)
printf("INF ");
else
printf("%3d ", adj[i][j]);
}
printf("\n");
}
}

int main()
{
int **adj,i,j,v ,e, bi;
printf("Number of vertices: ");
scanf("%d",&v);
adj = (int **)malloc(sizeof(int*)*v);
for(i = 0; i < v; i++){
adj[i] = (int *)malloc(sizeof(int)*v);
for(j = 0; j < v; j++){
if(i==j)
adj[i][j] = 0;
else
adj[i][j] = INFINITY;
}
}
printf("Number of edges: ");
scanf("%d",&e);
printf("Enter 0 if graph is Directed, else enter 1: ");
scanf("%d", &bi);
printf("Enter 2 vertices and correspoding weight for each edge:\n");
setAdgecencyMatrix(adj, e ,v, bi);
printAdjacencyMatrix(adj, v);
primMST(adj, v);

© Department of CSE Page 103 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

return 0;
}
OUTPUT:

© Department of CSE Page 104 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Kruskal’s Algorithm.
Solution: FlowChart

© Department of CSE Page 105 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

Time Complexity:

algorithm Kruskal(G) is
A := ∅
for each v ∈ G.V do
MAKE-SET(v)
for each (u, v) in G.E ordered by weight(u, v), increasing do
if FIND-SET(u) ≠ FIND-SET(v) then
A := A ∪ {(u, v)}
UNION(FIND-SET(u), FIND-SET(v))
return A

O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time.


After sorting, we iterate through all edges and apply find-union algorithm.
The find and union operations can take atmost O(LogV) time.
So overall complexity is O(ELogE + ELogV) time.
The value of E can be atmost O(V2), so O(LogV) are O(LogE) same.
Therefore, overall time complexity is O(ElogE) or O(ElogV)

C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Edge {
int u, v, weight;
};
struct Graph {
int V, E;
struct Edge* edge;
};

struct Graph* createGraph(int V, int E) {


struct Graph* graph;
graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*)malloc(sizeof(struct Edge)*E);
return graph;
}

struct subset {
int parent;
int rank;
};

int find(struct subset subsets[], int i) {


if (subsets[i].parent != i)
© Department of CSE Page 106 of
110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

subsets[i].parent = find(subsets, subsets[i].parent);


return subsets[i].parent;
}

void Union(struct subset subsets[], int x, int y) {


int xroot = find(subsets, x);
int yroot = find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank)


subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}

int myComp(const void* a, const void* b) { //For Sorting


struct Edge* a1 = (struct Edge*)a;
struct Edge* b1 = (struct Edge*)b;
return a1->weight > b1->weight;
}

int printMST(struct Edge result[], int e) {


int cost = 0, i;
printf("Edge \tWeight\n");
for (i = 0; i < e; ++i) {
printf("%d--%d \t%d\n", result[i].u, result[i].v, result[i].weight);
cost += result[i].weight;
}
printf("Cost: %d.\n", cost);
}

void KruskalMST(struct Graph* graph) {


int V = graph->V;
struct Edge result[V];
int e = 0;
int i = 0;
int v, x, y;

qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);


struct subset *subsets = (struct subset*) malloc( V * sizeof(struct subset) );

for (v = 0; v < V; ++v) {


subsets[v].parent = v;
subsets[v].rank = 0;
}

© Department of CSE Page 107 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

while (e < V - 1 && i < graph->E) {


struct Edge next_edge = graph->edge[i++];

x = find(subsets, next_edge.u);
y = find(subsets, next_edge.v);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}

printMST(result,e);
return;
}

int main()
{
int V, E;
printf("Number of vertices: ");
scanf("%d",&V);
printf("Number of edges: ");
scanf("%d",&E);
struct Graph* graph = createGraph(V, E);
int i;
printf("Enter 2 vertices and correspoding weight for each edge:\n");
for(i = 0; i<E; i++)
scanf("%d %d %d", &graph->edge[i].u, &graph->edge[i].v, &graph->edge[i].weight);

KruskalMST(graph);

return 0;
}

© Department of CSE Page 108 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

OUTPUT:

© Department of CSE Page 109 of


110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091

12.3. Show how to multiply the complex numbers a+bi and c+di (i is the imaginary number √(-1) using
only three multiplications of real numbers. Your code should take a,b,c and d as input and produce
the real component ac-bd and the imaginary component ad+bc separately.

Solution: FlowChart

Time Complexity:

The running time will be O(1) [Constant Time].


This is because the program has neither any loops nor any recursion involved.

C Code:
#include <stdio.h>
int main(){
int a,b,c,d,x,y,z;
printf("Enter the values of a, b, c & d: ");
scanf("%d%d%d%d", &a, &b, &c, &d);
x = a*c;
y = b*d;
z = (a+b)*(c+d);
printf("The product is: %d%+di.\n", (x-y),(z-x-y));
}

Output:

© Department of CSE Page 110 of


110

You might also like