You are on page 1of 51

CMR INSTITUTE OF TECHNOLOGY

Department of Computer Science & Engineering

IV Semester

10CSL47– DESIGN AND ANALYSIS OF ALGORITHMS LAB

ACADEMIC YEAR 2014 - 15[EVEN]

BY

MANIMOZHI. I

Associate professor

Department of computer science &Engg

CMR Institute of technolo

Bangalore
Subject Code : 10CSL47 I.A. Marks : 25

Hours/Week : 03 Exam Hours : 03

Total Hours : 42 Exam Marks : 50

Design, develop and implement the specified algorithms for the following problems using
C/C++ Language in LINUX /Windows environment.

1. Sort a given set of elements using the Quicksort method and determine the time required to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list to
be sorted and plot a graph of the time taken versus n.The elements can be read from a file or can be
generated using the random number generator.

2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements
and determine the time required to sort the elements. Repeat the experiment for different values of
n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the random number generator.

3. a. Obtain the Topological ordering of vertices in a given digraph.


b. Compute the transitive closure of a given directed graph using
Warshall's algorithm.

4. Implement 0/1 Knapsack problem using Dynamic Programming.

5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm.

6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method.
b. Check whether a given graph is connected or not using DFS method.

8. Find a subset of a given set S = {sl, s2,....., sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S={1, 2, 5, 6, 8} and d = 9 there are two
solutions{1,2,6}and{1,8}.A
suitable message is to be displayed if the given problem instance doesn't have a solution.

9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and
then solve the same problem instance using any approximation algorithm and determine the error
in the approximation.
10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm,
implement it using OpenMP and determine the speed-up achieved.

12. Implement N Queen's problem using Back Tracking.

1. Sort a given set of elements using the Quicksort method and determine the
time required to sort the elements. Repeat the experiment for different values
of n, the number of elements in the list to be sorted and plot a graph of the
time taken versus n.The elements can be read from a file or can be generated
using the random number generator.
#include<stdio.h>
#include<sys/time.h>
#include<stdlib.h>
#include<math.h>
structtimeval t;
double dt,dt1,dt2;
void quicksort();
int main()
{
inti,n,a[10];
printf("THE NUMBER TO BE ENTERED\n");
scanf("%d",&n);
printf("THE UNSORTED ARRAY IS\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
gettimeofday(&t,NULL);
dt1=t.tv_sec*pow(10,6)+t.tv_usec;
quicksort(a,0,n-1);
printf("THE SORTED ARRAY IS\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
gettimeofday(&t,NULL);
dt2=t.tv_sec*pow(10,6)+t.tv_usec;
dt=dt2-dt1;
printf("THE TIME TAKEN IS=%lf\n",dt);
}
int partition(int a[10],intlow,int high)
{
Int pivot, i,j,T;
pivot=a[low];
i=low;
j=high;
while(i<=j)
{
while(a[i]<=pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
T=a[i];
a[i]=a[j];
a[j]=T;
}
}
T=a[low];
a[low]=a[j];
a[j]=T;
return j;
}
void quicksort(int a[10],intlow,int high)
{
int k;
if(low<high)
{
k=partition(a,low,high);
quicksort(a,low,k-1);
quicksort(a,k+1,high);
}
}
OUTPUT

THE NUMBER TO BE ENTERED

THE UNSORTED ARRAY IS

1 8 4 9 3

THE SORTED ARRAY IS

1 3 4 8 9

THE TIME TAKEN IS=17.000000


2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a
given set of elements and determine the time required to sort the elements.
Repeat the experiment for different values of n, the number of elements in the
list to be sorted and plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.
#include<stdio.h>

#include<time.h>

#include<omp.h>

#define MAX 500000

void mergesort(int a[],int low, int high);

void merge(int a[],int low, int mid,int high);

main()

int i,a[MAX],ch=1;

clock_t start=0,end=0;

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

a[i]=rand();

printf("\n\t The elements are\n");

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

printf("%d\n",a[i]);
start= clock();

mergesort(a,0,MAX-1);

end = clock();

printf("\nthe sorted array is\n");

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

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

printf("\n\ntime taken=%g",(end-start)/(double)CLOCKS_PER_SEC);

void mergesort(int a[],int low, int high)

int mid,tid;

if(low<high)

#pragma omp parallel sections num_threads(5)

mid=(low+high)/2;

#pragma omp section

mergesort(a,low,mid);

#pragma omp section

mergesort(a,mid+1,high);

merge(a,low,mid,high);
}

void merge(int a[],int low, int mid,int high)

int i,j,k,t[MAX];

i=low;

j=mid+1;

k=low;

for(;(i<=mid) && (j<=high);)

if(a[i]<=a[j])

t[k++]=a[i++];

else

t[k++]=a[j++];

while(i<=mid)

t[k++]=a[i++];

while(j<=high)

t[k++]=a[j++];

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

a[i]=t[i];

}
OUTPUT
enter the number of elements
5
enter the elements
6
3
4
1
9
the sorted array is
1
3
4
6
9
time taken is =0.824176
3. a. Obtain the Topological ordering of vertices in a given digraph.

#include<iostream>
using namespace std;
classtopo
{
int n;
int a[10][10];
int indegree[10];
public:
void read_data();
void topo_sort();
};
Void topo::read_data()
{
cout<<"Enter the number of jobs"<<endl;
cin>>n;
cout<<"Enter the adjacency matrix"<<endl;

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
}
Void topo ::topo_sort()
{
Int u,v,t[10],s[10],sum;
int top=-1;
int k=0;
int i,j;
for(j=0;j<n;j++)
{
sum=0;
for(i=0;i<n;i++)
{
sum=sum+a[i][j];
indegree[j]=sum;
}
}
for(int i=0;i<n;i++)
{
if(indegree[i]==0)s[++top]=i;

}
while(top!=-1)
{
u=s[top--];
t[k++]=u;
for(int v=0;v<n;v++)
{
if(a[u][v]==1)
{
indegree[v]--;
if(indegree[v]==0)s[++top]=v;
}
}
}
cout<<"The topological sequence is:"<<endl;
for(int i=0;i<n;i++)
{
cout<<t[i]<<"\t";
}
cout<<endl;
}
int main()
{
topo t;
t.read_data();
t.topo_sort();
}
OUTPUT
Enter the number of jobs

Enter the adjacency matrix

0 0 1 1 0 0

0 0 0 1 1 0

0 0 0 1 0 1

0 0 0 0 0 1

0 0 0 0 0 1

0 0 0 0 0 0

The topological sequence is:

1 4 0 2 3 5
b. Compute the transitive closure of a given directed graph using Warshall's
algorithm.

#include<stdio.h>
#include<sys/time.h>
#include<math.h>
struct timeval t;
double dt1,dt2,dt;
int a[50][50],c[50][50];
void warshall(int n);
int main()
{ int n,i,j;
printf("enter the size of matrix\n");
scanf("%d",&n);
printf("enter the elements of matrix\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&c[i][j]);
printf("the given matrix is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
warshall(n);
printf("the transitive matrix closure is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)

{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
void warshall(int n)
{
int i,j,k;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=c[i][j];
}
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]==0&&(a[i][k]==1&&a[k][j]==1))
{
a[i][j]=1;
}
}
}
}
}
OUTPUT

enter the size of matrix

enter the elements of matrix

1 1 0 0

0 0 1 1

0 0 0 0

1 1 0 0

the given matrix is

1 1 0 0

0 0 1 1

0 0 0 0

1 1 0 0

the transitive matrix closure is

1 1 1 1

1 1 1 1

0 0 0 0

1 1 1 1
4. Implement 0/1 Knapsack problem using Dynamic Programming.

#include<iostream.h>
#include<stdlib.h>
#define MAX 30

int values[MAX],weights[MAX],v[MAX][MAX],x[MAX],n,m;

int max(int a, int b)


{
return (a>b)?a:b;
}

int MFKS(int i,int j)


{
int val;
if (v[i][j] == -1)
{
if (j<weights[i])
{
val = MFKS(i-1,j);
v[i][j] = val;
}
else
val = max(MFKS(i-1,j),MFKS(i-1,j - weights[i]) + values[i]);\
v[i][j] = val;
}
return v[i][j];
}

void svector()

{
int j1 = m;
for (int i = n;i>=0;i--)
if (v[i][j1]!=v[i-1][j1])
{
x[i] = 1;
j1 = j1 - weights[i];
}
cout<<"{";
for (j1=1;j1<=n;j1++)
cout<<x[j1]<<"\t";
cout<<"}\n";
}

void main()
{
int optsol;
cout<<"Enter the Number of items\n";
cin>>n;
cout<<"Enter the Weights\n";
for(int i=1;i<=n;i++)
cin>>weights[i];
cout<<"Enter the Values\n";
for(i=1;i<=n;i++)
cin>>values[i];
cout<<"Enter the Knapsack Capacity\n";
cin>>m;
for(i=0;i<=m;i++)
v[0][i] = 0;
for(i=0;i<=n;i++)
v[i][0] = 0;
for(i=1;i<=n;i++)
for(int j = 1;j<=m;j++)
v[i][j] = -1;
optsol = MFKS(n,m);
cout<<"Optimal Solution is "<<optsol<<endl;
cout<<"The Optimal Solution Vector is\n";
for (i=1;i<=n;i++)
x[i] = 0;
svector();
}
OUTPUT

Enter the Number of items


4
Enter the Weights
2
3
4
5
Enter the Values
78
45
92
71
Enter the Knapsack Capacity
6
Optimal Solution is 170
The Optimal Solution Vector is
{1 0 1 0 }
5. From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra's algorithm.

#include<stdio.h>
#include<math.h>
int a[10][10],p[10],d[10],n,src;
#include<sys/time.h>
struct timeval ti;
double t1,t2,t;
void main()
{
int i,j;
printf("Enter the number of vertices\n");
scanf("%d",&n);
printf("Enter the cost adjacency matrix. Enter 999 for infinite value\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the source vertex\n");
scanf("%d",&src);
gettimeofday(&ti,NULL);
t1=ti.tv_sec*pow(10,6)+ti.tv_usec;
dijikstra();
gettimeofday(&ti,NULL);
t2=ti.tv_sec*pow(10,6)+ti.tv_usec;
t=t2-t1;
print();

printf("time=%lf \n",t);
}

void dijikstra()
{
int i,j,u,v,min;
int s[10];
for(i=0;i<n;i++)
{
d[i]=a[src][i];
s[i]=0;
p[i]=src;
}
s[src]=1;
for(i=1;i<n;i++)
{
min=999;
u=-1;
for(j=0;j<n;j++)
{
if(s[j]==0)
{
if(d[j]<min)
{
min=d[j];
u=j;
}
s[u]=1;
}
}
for(v=0;v<n;v++)
{
if(s[v]==0)
{
if(d[u]+a[u][v]<d[v])
{
d[v]=d[u]+a[u][v];
p[v]=u;
}
}
}
}
}

void print()

{
int x,i;

printf("The shortest tree path\n");


for(i=0;i<n;i++)
{
if(d[i]!=999)
{
x=i;
while(x!=src)
{
printf("%d <-",x);
x=p[x];
}
printf("%d = %d \n",x,d[i]);
}
}
}
OUTPUT

Enter the number of vertices

Enter the cost adjacency matrix. Enter 999 for infinite value

0 15 10 999 999 999

999 0 999 999 20 999

20 999 0 26 999 999

999 10 999 0 35 999

999 999 999 20 0 999

999 999 999 4 999 0

Enter the source vertex

The shortest tree path

0  2 = 20

1  0  2 = 35

2=0

3  2 = 26

4  3  2 = 61

5  1  0  2 = 0

time=4.000000
6. Find Minimum Cost Spanning Tree of a given undirected graph using
Kruskal's algorithm.

#include<stdio.h>
int find(intv,int s[])
{
while(s[v]!=v)
{
v=s[v];
}
return v;
}
void kruskal(int n,int c[10][10])
{
Int count,I,s[10],min,j,u,v,k,t[10][10],sum;
for(i=0;i<n;i++)
s[i]=i;
count=0;
sum=0;
k=0;
while(count<n-1)
{
min=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(c[i][j]!=0&&c[i][j]<min)
{
min=c[i][j];
u=i;
v=j;

}
}
}
if(min=999)break;
i=find(u,s);
j=find(v,s);
if(u!=v)
{
t[k][0]=u;
t[k][1]=v;
k++;
count++;
sum+=min;
s[v]=u;
}
c[u][v]=c[v][u]=999;
}
if(count=n-1)
{
printf(“cost of spanning tree=%d\n”,sum);
printf(“spanning tree is shown below %d\n”,sum);
for(for(k=0;k<n-1;k++)
{
printf(“%d,%d\n”,t[k][0],t[k][1]);
}
exit(0);
}
printf(“spanning tree do not exist\n”);
}
void main()
{
intn,c[10][10],i,j;
printf(“enter the no. of nodes”);
scanf(“%d”,&n);
printf(“enter the cost adjacency matrix\n”);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf(“%d”,&c[i][j]);
kruskal(n,c);
}
OUTPUT

enter the no. of nodes

enter the cost adjacency matrix

0 3 999 999 6 5

3 0 1 999 999 4

999 1 0 6 999 4

999 999 6 0 8 5

6 999 999 8 0 2

5 4 4 5 2 0

cost of spanning tree=15

spanning tree is shown below 15

2,3

5,6

1,2

2,6

4,6
7. a. Print all the nodes reachable from a given starting node in a digraph
using BFS method.

#include<stdio.h>

Void bfs(int n,int c[10][10])

Int vis[10],f=0,r=0,q[10],source=0,u,v,i,j;

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

vis[i]=0;

q[r]=source;

vis[source]=1;

while(f<=r)

u=q[f++];

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

if(c[u][v]==1&&vis[v]==0)

vis[v]=1;

q[++r]=v;

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

{
if(vis[i]==0)

printf("vertex %d is not reachable\n",i);

else

printf("vertex %d is reachable\n",i);

void main()

intn,c[10][10],i,j,source;

printf("enter the number of nodes in the graph\n");

scanf("%d",&n);

printf("enter the cost adjacency matrix\n");

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

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

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

printf("Enter the source\n");

scanf("%d",&source);

bfs(n,c);

}
OUTPUT

enter the number of nodes in the graph

10

enter the cost adjacency matrix

0 1 1 1 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 0

0 0 0 0 0 1 0 0 0 0

0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 1 0

0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

Enter the source

vertex 0 is reachable

vertex 1 is reachable

vertex 2 is reachable

vertex 3 is reachable

vertex 4 is reachable

vertex 5 is reachable

vertex 6 is reachable
vertex 7 is reachable

vertex 8 is reachable

vertex 9 is reachable
b. Check whether a given graph is connected or not using DFS method.
#include<stdio.h>

Void dfs(int a[10][10],int n,int u,int v[10])

Int k,j,i,flag,s[10];

v[u]=1;

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

if(a[u][i]==1 && s[i]==0 && u!=i)

dfs(a,n,i,v);

void main()

int a[10][10],v[10],n,i,j,k,flag=1;

printf("enter the number of nodes in graph\n");

scanf("%d",&n);

printf("enter the adjacency matrix of graph\n");

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

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

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

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

v[i]=0;

dfs(a,n,i,v);

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

if(v[k]==0)

flag=1;

if(flag==1)

printf("graph is connected\n");

else

printf("graph is not connected\n");

}
OUTPUT

enter the number of nodes in graph

enter the adjacency matrix of graph

0 1 1 0

0 0 0 0

0 0 0 1

0 1 0 0

graph is connected
8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose
sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and
d = 9 there are two solutions{1,2,6}and{1,8}.A suitable message is to be
displayed if the given problem instance doesn't have a solution.

#include<stdio.h>
int subset(int n,int d,int w[]);
int main()
{
int n,d,i,w[10];
printf("Enter the no. of elements : ");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("Enter the sum value : ");
scanf("%d",&d);
subset(n,d,w);
return 0;
}
int subset(int n,int d,int w[])
{
int s,k,i,x[10];
for(i=1;i<=n;i++)
x[i]=0;
s=0;
k=1;
x[k]=1;
while(1)
{
if(k<=n && x[k]==1)
{
if(s+w[k]==d)
{
printf("Solution is \n");
for(i=1;i<=n;i++)
{
if(x[i]==1)
printf("%d ",w[i]);
}
printf("\n");
x[k]=0;
}
else if(s+w[k]<d)
s+=w[k];
else
x[k]=0;
}
else
{
k--;
while(k>0 && x[k]==0)
{
k--;
}
if(k==0)
break;
x[k]=0;
s=s-w[k];
}
k=k+1;
x[k]=1;
}
return;
}
OUTPUT

Enter the no. of elements : 4

Enter the elements

1 2 5 7

Enter the sum value : 8

Solution is : 1 2 5

Solution is : 1 7
9. Implement any scheme to find the optimal solution for the Traveling
Salesperson problem and then solve the same problem instance using any
approximation algorithm and determine the error in the approximation.
#include<iostream>
using namespace std;
#define max 10
int path[max];
int l=0;
int count =0;
int perm[120][7];
int tourcost[120];
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void dfs(int cv, int v[max], int g[max][max], int n)
{
int i;
v[cv]=1;
path[l++]=cv;
for(i=0;i<n;i++)
if(g[cv][i] && !v[i])
dfs(i,v,g,n);
}
void permute(int *a, int i, int n)
{
int j,k;
if(i==n)
{
for(k=0;k<=n;k++)
{
perm[count][k+1]=a[k];
}
count++;
}
else
{
for(j=i;j<=n;j++)
{
swap(a+i,a+j);
permute(a,i+1,n);
swap(a+i,a+j);
}
}
}
int apptsp(int n, int cost[max][max])
{
int i,j,u,v,min,excost=0;
int sum,k,t[max][2],p[max],d[max],s[max],tree[max][max];
int source,count;
int visited[max];
for(i=0;i<n;i++)
visited[i]=0;
min=9999;
source =0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(cost[i][j]!=0 && cost[i][j]<=min)
{
min=cost[i][j];
source=i;
}
}
}
for(i=0;i<n;i++)
{
d[i]=cost[source][i];
s[i]=0;
p[i]=source;
}
s[source]=1;
sum=0; k=0; count=0;
while(count!=n-1)
{
min=9999;
u=-1;
for(j=0;j<n;j++)
{
if(s[j]==0)
{
if(d[j]<=min)
{
min=d[j];
u=j;
}
}
}
t[k][0]=u;
t[k][1]=p[u];
k++;
count++;
sum+=cost[u][p[u]];
s[u]=1;
for(v=0;v<n;v++)
{
if(s[v]==0 && cost[u][v]<d[v])
{
d[v]=cost[u][v];
p[v]=u;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
tree[i][j]=0;
}
}
if(sum>=9999)
cout<<"\nSpanning tree does not exist";
else
{
for(i=0;i<k;i++)
{
tree[t[i][0]][t[i][1]] = tree[t[i][1]][t[i][0]] = 1;
}
}
dfs(0,visited,tree,n);
cout<<endl<<"The approx min cost tour is "<<endl;
for(i=0;i<=k;i++)
{
cout<<path[i]<<"->";
excost+=cost[path[i]][path[i+1]];
}
cout<<path[0];
excost+=cost[path[i]][path[0]];
cout<<endl<<"the approx min cost of the tour is " <<excost<<endl;
return excost;
}
int main(void)
{
int a[max][max] = {{0,4,8,9,12},
{4,0,6,8,9},
{8,6,0,10,11},
{9,8,10,0,7},
{12,9,11,7,0}};
int num_of_city=5;
int inter_cities=4,i,j;
int mct=999,mctIndex,Appmct;
int city[4]={1,2,3,4};
permute(city,0,inter_cities-1);
for(i=0;i<24;i++)
{
for(j=0;j<5;j++)
{
tourcost[i]+=a[perm[i][j]][perm[i][j+1]];
}
if(mct>tourcost[i])
{
mct=tourcost[i];
mctIndex=i;
}
}
cout<<endl<<"The exact min cost tour is "<<endl;
for(i=0;i<num_of_city;i++)
cout<<perm[mctIndex][i]<<"->";
cout<<perm[mctIndex][i];
cout<<endl<<"The exact min cost of the tour is " <<mct<<endl;
Appmct=apptsp(num_of_city,a);
cout<<"\nThe error in approx is "<<Appmct-mct<<" units"<<endl;
cout<<"\nThe accuracy ratio is " <<(float)Appmct/mct<<endl;
cout<<"\nThe approximate tour is "<<(((float)Appmct/mct)-1)*100<<" percent
longer than the optimal tour" <<endl;
return 0;
}
OUTPUT

The exact min cost tour is


0 1  2 4 3  0
The exact min cost of tour is 37
The approximate min cost tour is
0 1  23 4 0
The approximate min cost of tour is 39
The error in approximation is 2 units
The accuracy ratio is 1.05405
The approximate tour is 5.40541 longer than the optimal tour
10. Find Minimum Cost Spanning Tree of a given undirected graph using
Prim’s algorithm.

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

const int max=15;


class stree
{
int p,q,m,n,min1,spn[max],reach[max];
int cost[max][max],t[max][2];
public:
stree()
{
m=0;
}
void costmat();
int prim();
void minedge();
void print();
int empty();
};

/* function to read the cost matrix */


void stree :: costmat()
{
cout<<"\nEnter the number of vertices"<<endl;
cin>>n;
cout<<"\nEnter the cost adacency matrix\n"
<<"\nEnter -1 for no edges\n";

for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>cost[i][j];
}

/* function to find the minimum cost path */


int stree :: prim()
{
int i,mincost=0;
++m;
spn[1]=1;
minedge();
for(i=1;i<=n;i++)
reach[i]=0;
i=0;
reach[1]=1;
while(i<(n-1) && !empty())
{
cost[p][q]=-1;
cost[q][p]=-1;
if(!reach[q])
{
reach[q]=1;
i=i+1;
t[i][1]=p;
t[i][2]=q;
spn[++m]=q;
mincost+=min1;
}
minedge();
}
if(i!=(n-1))
{
cout<<"\nNo spanning tree";
return 0;
}
else
return mincost;
}

void stree :: minedge()


{
int i=1,j,k;
int min=999;
while(i<=m)
{

j=spn[i];
for(k=1;k<=n;k++)
{
if(cost[j][k]!=-1)
{
if(cost[j][k]<min)
{
min=cost[j][k];
p=j;
q=k;
}
}
}
i++;
}
min1=min;
}

int stree :: empty()


{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(cost[i][j]!=-1)
return 0;
}
}
return 1;
}

void stree :: print()


{
for(int i=1;i<n;i++)
cout<<"\n<"<<t[i][1]<<">--<"<<t[i][2]<<">";
}

void main()
{
stree s;
s.costmat();
int cost=s.prim();
if(cost!=0)
{

cout<<"Cost of minimum spanning tree ="<<cost;


cout<<endl;
cout<<"\nThe Minimum Spanning Tree is ";
s.print();
cout<<endl;
}
}

OUTPUT

Enter the number of vertices


4

Enter the cost adacency matrix

Enter -1 for no edges


-1 10 50 -1
-1 -1 40 20
-1 -1 -1 30
-1 -1 -1 -1
Cost of minimum spanning tree = 70

The Minimum Spanning Tree is


<1>--<2>
<2>--<4>
<2>--<3>
11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Parallelize this algorithm, implement it using OpenMP and determine the
speed-up achieved.

#include,stdio.h>
#include<sys/time.h>
struct timeval t;
double dt1,dt2,dt;
int min(int a,int b)
{
return a<b?a:b;
}
void floyd (int p[10][10],int n)
{
int i,j,k;
omp_set_num_threads(2);
#pragma omp parallel for
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
printf("\nk=%d,thread id=
%d",k,omp_set_num_threads());
}
}
}

void main()
{

int a[4][4],i,j,n;
printf("enter the no of vertices\n");
scanf("%d",&n);
printf("enter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
gettimeofday(&t,NULL);
t1=t.tv_sec*pow(10,6)+t.tv_usec;
floyd(a,n);

gettimeofday(&t,NULL);
t2=t.tv_sec*pow(10,6)+t.tv_usec;
dt=t2-t1;

floyd(a,n);
printf("the resultant matrix is \n");
for(i=1;i<=n;i++)
for (j=1;j<=n;j++)
printf("%d\t",a[i][j]);
printf("\n");
printf("Time taken to find the shortest path is %f\n",dt);
}
OUTPUT

Enter the no of vertices:


4
Enter the cost matrix
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0
The resultant matrix is
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
Time taken to find the shortest path is 68.455643
12. Implement N Queen's problem using Back Tracking.

#include<stdio.h>
void queens(int);
void PrintBoard(int);
int x[20],soln=1;
int main()
{
int n;
printf("Enter the no. of queens to place : ");
scanf("%d",&n);
queens(n);
return 0;
}
void queens(int n)
{
int i,k=1;
x[k]=0;
while(k!=0)
{
x[k]=x[k]+1;
while(x[k]<=n && !place(k,x))
x[k]=x[k]+1;
if(x[k]<=n)
if(k==n)
PrintBoard(n);
else
k++,x[k]=0;
else
k--;
}
printf("\nThe number of possible solutions are %d",soln-1);
}

int place(int k,int x[])


{
int i;
for(i=1;i<k;i++)
if((x[i]==x[k]) || (i-x[i]==k-x[k]) || (i+x[i]==k+x[k]))
return 0;
return 1;
}

void PrintBoard(int n)
{
int i,j;
printf("\n Solution set %d: ",soln);
for(i=1;i<=n;i++)
printf(" %d ",x[i]);
printf("\n\n Placements are as shown below: \n\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
(j==x[i]) ? printf(" Q%d ",i) : printf(" -- ");
printf("\n");
}
soln++;
}
OUTPUT

Enter the number of queens to place : 4

Solution set 1 : 2 4 1 3

Placements are as shown below

-- Q1 -- --

-- -- -- Q2

Q3 -- -- --

-- -- Q4 --

Solution set 2 : 3 1 4 2

Placements are as shown below

-- -- Q1 --

Q2 -- -- --

-- -- -- Q3

-- Q4 -- --

The number of possible solutions are 2

You might also like