Sie sind auf Seite 1von 78

dPROGRAM 1

// Program for finding Longest Common Subsequence

#include<stdio.h>
#include<curses.h>
#include<string.h>
#include<process.h>
void print_lcs(int b[10][10],char x[10],int i, int j);

int main()
{
clrscr();
int a,I,j,m,n,g,h,b[10][10];
char c[10][10];
char x[10],y[10];
printf(“\n Enter the length of sequence of x: “);
scanf(“%d”,&g);
printf(“\n Enter the length of sequence of y: “);
scanf(“%d”,&h);
printf(“\n Enter sequence x: “);
for(a=1;a<=g;a++)
scanf(“%d”,&x[a]);
printf(“\n Enter sequence y: “);
for(a=1;a<=h;a++)
scanf(“%d”,&y[a]);
for(i=1;i<=g;i++)
c[i][0]=0;
for(j=1;j<=h;j++)
c[0][j]=0;
for(i=1;i<=g;i++)
{
for(j=1;j<=h;j++)
{
if(x[i]==y[j])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]=0;
}
else
{
if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]=1;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 1


else
{
c[i][j]=c[i][j-1];
b[i][j]=2;
}
}
}
}
i=i-1;
j=j-1;
print_lcs(b,x,I,j);
int getch();
}

void print_lcs(int b[10][10],char x[10],int I,int j)


{
if(i==0 || j==0)
return;
if(b[i][j]==0)
{
printf(“%d”,x[i]);
print_lcs(b,x,i-1,j-1);
}
else if(b[i][j]==1)
print_lcs(b,x,i-1,j);

else if(b[i][j]=2)
print_lcs(b,x,I,j-1);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 2


OUTPUT

Enter the length of sequence of x: 4

Enter the length of sequence of y: 3

Enter the sequence x: a b c d

Enter the sequence y: b c e

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 3


PROGRAM 2

// Program to implement Matrix Chain Multiplication

#include<iostream.h>

int m[20][20];
int num=1;

void mat_disp(int j,int i)


{
if(i>j)
{
cout<<"(";
mat_disp(j,m[i][j]);
mat_disp(m[i][j]+1,i);
cout<<")";
}
else if(i==j)
cout<<'A'<<i+1;
//cout<<")";
}

void mat_chain(int n,int p[])


{
int i,j,k,l,temp,flag,min;
for(i=0,j=0;i<n;i++,j++)
m[i][j]=0;

for(l=1;l<n;l++)
{
for(i=0,j=l;i<n-l;i++,j++)
{
min=(m[i][i]+m[i+1][j]+(p[i]*p[i+1]*p[j+1]));
flag=i;
for(k=i+1;k<j;k++)
{
temp=(m[i][k]+m[k+1][j]+
(p[i]*p[k+1]*p[j+1]));
if(min>temp)
{
min=temp;
flag=k;
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 4


m[i][j]=min;
m[j][i]=flag;
}
}

mat_disp(0,n-1);
}

int main()
{
int n;
int p[20];
cout<<"\n Enter the number of matrices to be multplied :
";
cin>>n;
cout<<"\n Enter the order sequence of matrices : ";
for(int i=0;i<=n;i++)
cin>>p[i];
cout<<"\n Optimal Pranthesization is:";
mat_chain(n,p);
return 0;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 5


OUTPUT

Enter the number of matrices to be multplied : 6

Enter the order sequence of matrices : 30 35 15 5 10 20 25

Optimal Paranthesization is: (A1((A2A3)((A4A5)A6)))

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 6


PROGRAM 3

//Program to implement Min Max

#include <iostream.h>

int min(int A[10])


{
int m=A[0];
for(int i=1;i<10;i++)
if(A[i]<m)
m=A[i];
return m;
}

int max(int A[10])


{
int m=A[0];
for(int i=1;i<10;i++)
if(A[i]>m)
m=A[i];
return m;
}

int main()
{
int A[10];
int min(int *), minm;
int max(int *), maxm;
cout<<"Enter the values of the array\n";
for(int i=0;i<10;i++)
cin>>A[i];
minm=min(A);
maxm=max(A);
cout<<"\nMinimum = "<<minm<<endl;
cout<<"\nMaximum = "<<maxm<<endl;
system("PAUSE");
return 0;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 7


OUTPUT

Enter the values of the array


1
5
10
3
7
9
112
55
12
33
Minimum = 1
Maximum = 112

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 8


PROGRAM 4

// Program To Implement Naive String Matching

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char mstr[20];
char pstr[20];
int n,m;
int s,i,flag=0,j;
cout<<"\n\nEnter Main String : ";
cin>>mstr;
cout<<"\n\nEnter Pattern String : ";
cin>>pstr;
n=strlen(mstr);
m=strlen(pstr);
for(s=0;s<=(n-m);s++)
{
flag=0;
j=0;
while(!flag && (j<m))
{
if(pstr[j]!=mstr[j+s])
flag=1;
else
j++;

}
if(!flag)
cout<<"\nPattern Exists With
Shift :"<<s<<"\n";

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 9


OUTPUT

Enter Main String : abaabba

Enter Pattern String : aba

Pattern Exists With Shift :0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 10


PROGRAM 5

// Program To Implement Rabin Karp String Matching

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<math.h>
#include<conio.h>
void main()
{
clrscr();

double mstr;
int pstr;
int j;
cout<<"\nEnter Main Text : ";
cin>>mstr;
cout<<"\nEnter Pattern Text : ";
cin>>pstr;
int p=pstr % 13;
int q=0;
//To Know The No. Of Digits In Pattern Text
int n=pstr;
int dp=0;
while(n)
{
n=n/10;
dp++;
}
//This Logic Ends Here
//To Know The No. Of Digits In Main Text
int m=mstr;
int dm=0;
while(m)
{
m=m/10;
dm++;
}
//This Logic Ends Here

int s=0;
double marray[20],parray[20];
m=mstr;n=pstr;
int d,i;
for(i=dm;i>=0;i--)

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 11


{
d=m % 10;
marray[i]=d;
m=m / 10;
}
for(i=dp;i>=0;i--)
{
d=n % 10;
parray[i]=d;
n=n / 10;
}

for(s=1;s<=(dm-dp+1);s++)
{
i=dp+s-1;
j=0;
n=0;
while(i>=s)
{
n=n+(pow(10,j)*marray[i]);
i--;
j++;
}
q=int(n) % 13;
if(q==p) //checking the case of spurious hit
{
int flag=0;
int k=1;
while(!flag && (k<=dp))
{
if(parray[k]!=marray[k+s-1])
flag=1;
else
k++;

}
if(!flag)
cout<<"\nPattern Exists With Shift :"<<s-1<<"\n";

}
}
getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 12


OUTPUT

Enter Main Text : abaaba

Enter Pattern Text : aba

Pattern Exists With Shift :0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 13


PROGRAM 6

// To determine solution to Knapsack problem

#include<stdio.h>
#include<curses.h>
#include<process.h>
void sort(float t[10],int n,float p[10],float w[10]);

int main()
{
clrscr();
int i,n,m,s,t;
float x[10],w[10],u,p[10],sum=0.0,tr[10];
printf(“\n Enter the size of knapsack bag: “);
scanf(“%d”,&m);
printf(“\n Enter the no. of items: “);
scanf(“%d”,&n);
printf(“\n Enter the weight of each items: “);
for(i=0;i<n;i++)
{
printf(“\nw[%d]: “,i);
scanf(“%d”,&w[i]);
}
printf(“\n Enter the profit of each items: “);
for(i=0;i<n;i++)
{
printf(“\np[%d]: “,i);
scanf(“%d”,&p[i]);
}
for(i=0;i<n;i++)
x[i]=0.0;
u=m;
for(s=0;s<n;s++)
{
tr[s]=p[s]/w[s];
}
sort(tr,n,p,w);
for(i=0;i<n;i++)
{
if(u>=w[i])
{
x[i]=1;
u=u-w[i];
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 14


t=u;
if(u<m)
{
for(i=0;<n;i++)
{
if(x[i]==0 && u>0)
{
x[i]=2;
u=u-t;
}
}
}
for(i=0;i<n;i++)
{
if(x[i]==1)
{
sum=sum+p[i];
}
if(x[i]==2)
{
sum=sum+((t/w[i])*p[i]);
}
}
printf(“\n Profit: %d”,sum);
int getch();
}

void sort(float t[10],int n,float p[10],float w[10])


{
float i,big,pos,j,temp,m,temp1,x,temp2;
for(i=0;i<n-1;i++)
{
big=t[i];
pos=i;
for(j=i+1;j<n;j++)
{
if(big<t[j])
{
big=t[j];
pos=j;
}
}
temp=t[i];
t[i]=t[pos];
t[pos]=temp;
temp1=p[i];
p[i]=p[pos];

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 15


p[pos]=temp1;
temp2=w[i];
w[i]=w[pos];
w[pos]=temp2;
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 16


OUTPUT:

Enter the size of knapsack bag: 20

Enter the no. of items: 3

Enter the weight of each item:

w[0] = 18

w[1] = 15

w[2] = 10

Enter the profit of each item:

p[0] = 25

p[1] = 24

p[2] = 15

Profit: 31.5

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 17


PROGRAM 7

// Write a program to implement Floyd Warshall algorithm

#include<stdio.h>
#include<curses.h>
#include<stdlib.h>
int min(int e,int f);

int main()
{
clrscr();
int n,m,b,c,d,i,j,a[10][10],pi[10][10];
printf(“\n Enter the no. of rows and column: “);
scanf(“%d %d”,&m,&n);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
scanf”%d”,&a[i][j]);
}
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
{
if(i==j |\ a[i][j]>=100)
p[i][j]=0;
else
pi[i][i]=i;
printf(“ %d”,pi[i][j]);
}
}
for(b=1;b<=m;b++)
{
for(c=1;c<=m;c++)
{
for(d=1;d<=m;d++)
{
if(a[c][d]<=a[c][b]+a[b][d])
pi[c][d]=pi[b][d];
a[c][d]=min(a[c][d],a[c][b]+a[b][d]);
}
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 18


printf(“\n\nThe resultant shortest weight matrix is:
\n\n”);
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
printf(“%d”,a[i][j];
}
printf(“\n\nThe resultant intermediate vertex matrix
is: \n\n”);
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
printf(“%d”,pi[i][j];
}
int getch();
}

int min(int e,int f)


{
return((e<f) ? e : f);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 19


OUTPUT:

Enter the no. of rows and columns: 5 5


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

The resultant shortest weight matrix is:

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

The resultant intermediate vertex matrix is:

0 3 4 5 1
4 0 4 2 1
4 3 0 2 1
4 3 4 0 1
4 3 4 5 0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 20


PROGRAM 8

// Write a program to implement Activity Selection problem

#include<stdio.h>
#include<curses.h>

int main()
{
clrscr();
int n,s[15],f[15],m,i;
char A[15];
printf(“\n Enter the no. of activities: “);
scanf(“%d”,&n);
printf(“\n Enter the start values of activities: “);
for(i=1;i<=n;i++)
scanf(“%d”,&s[i]);
printf(“\n Enter the finishing values of activities:
“);
for(i=1;i<=n;i++)
scanf(“%d”,&f[i]);
for(i=1;i<=n;i++)
{
A[i]=96+i;
printf(“\n %s=(%d,%d)”,A[i],i,f[i]);
}
i=1;
printf(“ \n “);
printf(A[1]);
for(m=2;m<=n;m++)
{
if(s[m]>=f[i])
{
i=m;
printf(A[m]);
}
}
int getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 21


OUTPUT

Enter the no, of activities: 5


Enter the start value of activities: 1 3 0 5 3
Enter the finishing value of the activities: 4 5 6 7 8

a = (1,4)
b = (3,5)
c = (0,6)
d = (5,7)
e = (3,8)

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 22


PROGRAM 9

// Program to find the Shortest Path

#include<stdio.h>
#include<curses.h>
void relax(intd[10],int w[25][25],int p[10],int t);

int main()
{
clrscr();
int n,I,j,wt[25][25],d[10],pi[10],x;
printf(“\n Enter the no. of vertices (0<n<6): “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j)
{
printf(“\nweight[%d][%d]: “,I,j);
scanf(“%d”,&wt[i][j]);
}
}
}
printf(“\n Assume source node is 0th vertex “);
for(x=1;x<n;x++)
{
d[x]=100;
pi[x]=NULL;
}
d[0]=0;
pi[0]=NULL;
relax(d,wt,pi,n);
printf(“\n This is the path followed “);
int getch();
}

void relax(int d[10],int w[25][25],int p[10],int t)


{
int m,n,q;
for(q=0;q<2;q++)
{
for(n=0;n<t;n++)

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 23


{
for(m=0;m<t;m++)
{
if(n!=m && w[n][m]!=0)
{
if(d[m]>d[n]+w[n][m])
{
d[m]=d[n]+w[n][m];
p[m]=n;
printf(“\np[%d]: %d”,m,p[m]);
}
}
}
}
}
printf(“\n%d”,t-1);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 24


OUTPUT

Enter the no. of vertices (0<n<6): 3

weight[0][1]: 5

weight[0][2]: 7

weight[1][0]: 0

weight[1][2]: -2

weight[2][0]: 0

weight[2][1]: 0

Assume source node is 0th vertex


:0
:1
:2
This is the path followed

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 25


PROGRAM 10

// Program to find out the multiplication of matrices using strassen’s


algorithm

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

int m3[2][2],m1[2][2],m2[2][2];
int p[6];

void mat_accept(int mat[ ][2])


{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
cin>>mat[i][j];

void mat_display(int mat[ ][2])


{
int i,j;
for(i=0;i<2;i++)
{
cout<<"\n\n";
for(j=0;j<2;j++)
cout<<'\t'<<mat[i][j];
}
}

void mat_multiply(int m1[ ][2],int m2[ ][2])


{
p[0]=m1[0][0]*(m2[0][1]-m2[1][1]);
p[1]=(m1[0][0]+m1[0][1])*m2[1][1];
p[2]=(m1[1][0]+m1[1][1])*m2[0][0];
p[3]=m1[1][1]*(m2[1][0]-m2[0][0]);
p[4]=(m1[0][0]+m1[1][1])*(m2[0][0]+m2[1][1]);
p[5]=(m1[0][1]-m1[1][1])*(m2[1][0]+m2[1][1]);
p[6]=(m1[0][0]-m1[1][0])*(m2[0][0]+m2[0][1]);

m3[0][0]=p[4]+p[3]-p[1]+p[5];
m3[0][1]=p[0]+p[1];
m3[1][0]=p[2]+p[3];
m3[1][1]=p[4]+p[0]-p[2]-p[6];

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 26


cout<<"\n The resultant matrix is : ";
mat_display(m3);
}

int main( )
{
clrscr( );
int i,j;

cout<<"\n Enter the values in the first 2x2 matrix : ";


mat_accept(m1);
cout<<"\n Enter the values in the second 2x2 matrix : ";
mat_accept(m2);

mat_multiply(m1,m2);
getch( );
return 0;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 27


OUTPUT

Enter the values in the first 2*2 matrix: 2


1
2
1
Enter the values in the second 2*2 matrix: 2
1
1
1

The resultant matrix is: 5 3 5 3

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 28


PROGRAM 11

// WAP to implement insertion sort

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int k,a[5],i,j,temp;
for(i=0;i<5;i++)
{
cout<<"\nEnter value of array a["<<i<<"] : ";
cin>>a[i];
}
cout<<"\nArray after sorting is: ";
for(k=1;k<5;k++)
{
temp=a[k];
j=k-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
for(i=0;i<5;i++)
cout<<"\n value of array a["<<i<<"] : "<<a[i];
getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 29


OUTPUT

Enter value of array a[0] : 2


Enter value of array a[1] : 8
Enter value of array a[2] : 4
Enter value of array a[3] : 6
Enter value of array a[4] : 0
Array after sorting is:
value of array a[0] : 0
value of array a[1] : 2
value of array a[2] : 4
value of array a[3] : 6
value of array a[4] : 8

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 30


PROGRAM 12

// WAP to implement Merge Sort

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int arr[100];
void merge(int f1, int l1,int f2,int l2)
{
int i=f1;
int j=f2;
int temp[100],k=0;
while(i<=l1 && j<=l2)
{
if(arr[i]<arr[j])
{
temp[k]=arr[i];
i++,k++;
}
else
{
temp[k]=arr[j];
j++,k++;
}
}
while(i<=l1)
{
temp[k]=arr[i];
k++,i++;
}
while(j<=l2)
{
temp[k]=arr[j];
k++,j++;
}
for(i=f1,k=0;i<=l2;i++,k++)
arr[i]=temp[k];
}
void mergesort(int f,int l)
{
int m;
if(l>f)
{
m=(f+l)/2;

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 31


mergesort(f,m);
mergesort(m+1,l);
merge(f,m,m+1,l);
}
}
void main()
{
clrscr();
int n,i,j=0;
cout<<"\n Enter number of terms: ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\nEnter value for a["<<i<<"] : ";
cin>>arr[i];
}
mergesort(j,n-1);
cout<<"\n\nSorted array is: ";
for(i=0;i<n;i++)
cout<<"\nValue for a["<<i<<"] : "<<arr[i];
getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 32


OUTPUT

Enter number of terms: 5


Enter value for a[0] : 2
Enter value for a[1] : 6
Enter value for a[2] : 1
Enter value for a[3] : 9
Enter value for a[4] : 5
Sorted array is:
Value for a[0] : 1
Value for a[1] : 2
Value for a[2] : 5
Value for a[3] : 6
Value for a[4] : 9

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 33


PROGRAM 13

// WAP to implement Quick Sort

#include <iostream>
#define n 10

using namespace std;

int main()
{
int A[n]={45,92,37,33,95,78,26,48,82,63};
void quicksort(int [n], int, int);
quicksort(A,0,n-1);
cout<<"The sorted array is";
for(int i=0;i<n;i++)
cout<<A[i]<<" ";
system("PAUSE");
return 0;
}

void quicksort(int A[n], int p, int r)


{
int partition(int [n],int , int );
int q;
if(p<r)
{
q=partition(A,p,r);
quicksort(A,p,q-1);
quicksort(A,q+1,r);
}
}

int partition(int A[n], int p, int r)


{
int x,i;
x=A[r]; i=p-1;
int temp;
for(int j=p;j<=r-1;j++)
{
if(A[j]<=x)
{
i++;
temp=A[i];
A[i]=A[j];

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 34


A[j]=temp;
}
}
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
return i+1;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 35


OUTPUT

the unsorted sequence: 45


92
37
33
95
78
26
48
82
63

The sorted array is 26 33 37 45 48 63 78 82 92 95

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 36


PROGRAM 14

// WAP to implement Randomized Quick Sort

#include <iostream>
#define n 10

using namespace std;

int main()
{
int A[n]={45,92,37,33,95,78,26,48,82,63};
void quicksort(int [n], int, int);
quicksort(A,0,n-1);
cout<<"The sorted array is";
for(int i=0;i<n;i++)
cout<<A[i]<<" ";
system("PAUSE");
return 0;
}

void quicksort(int A[n], int p, int r)


{
int rand_partition(int [n],int , int );
int q;
if(p<r)
{
q=rand_partition(A,p,r);
quicksort(A,p,q-1);
quicksort(A,q+1,r);
}
}

int rand_partition(int A[n], int p, int r)


{
int partition(int *,int , int);
int i=rand()%100;
while(!((i<=r)&&(i>=p)))
i=rand()%100;
int temp;
temp=A[r];
A[r]=A[i];
A[i]=temp;
return partition(A,p,r);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 37


int partition(int A[n], int p, int r)
{
int x,i;
x=A[r]; i=p-1;
int temp;
for(int j=p;j<=r-1;j++)
{
if(A[j]<=x)
{
i++;
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
return i+1;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 38


OUTPUT

the unsorted sequence: 45


92
37
33
95
78
26
48
82
63

The sorted array is 26 33 37 45 48 63 78 82 92 95

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 39


PROGRAM 15

// WAP to implement largest common subsequence from two given


sequences

#include<iostream.h>
#include<string.h>

int print_lcs(char b[20][20],char x[10],int i,int j)


{
if(i==-1||j==-1)
{
return 1;
}

if(b[i][j]=='a')
{
print_lcs(b,x,i-1,j-1);
cout<<x[i];
}

else if(b[i][j]=='b')
{
print_lcs(b,x,i-1,j);
}

else
print_lcs(b,x,i,j-1);
return 0;
}

int main()
{
char x[20],y[20],c[20][20];
int m,n,i,j;
char b[20][20];

cout<<"\nEnter the size of X and Y";


cin>>m>>n;
cout<<"\nEnter the elements of X...";
for(i=0;i<m;i++)
{
cin>>x[i];

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 40


}
cout<<"\nEnter the elements of Y...";

for(i=0;i<n;i++)
{
cin>>y[i];
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][-1]=0;
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[-1][j]=0;
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(x[i]==y[j])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]='a';
}

else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]='b';
}

else
{
c[i][j]=c[i][j-1];
b[i][j]='c';
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 41


}

cout<<"\nLCS is...";
print_lcs(b,x,i,j);
return 0;
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 42


OUTPUT

Enter the size of X and Y: 6 7

Enter the elements of X: b d c a b a

Enter the elements of Y: a b c b d a b

LCS is: b c b a

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 43


PROGRAM 16

// Write a program to find the median in a given set of numbers

#include<stdio.h>
#include<conio.h>
void main()
{
int a[30],n,i,j,p,d,temp,med1,med2,q;
clrscr();
printf("enter the no. of elements:\n");
scanf("%d",&n);
printf("enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
printf("the elements after sorting are :\n");
for(i=0;i<n;i++)
printf("%d,",a[i]);
d=n%2;
if(d==0)
{
p=n/2;
q=((n/2)-1);
med1=a[p];
med2=a[q];
}
else
{
p=(n-1)/2;
med1=a[p];
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 44


if(d==0)
{
printf("\nthe upper medians %d and lower medians
%d",med1,med2);
}
else
{
printf("\nthe medians %d ",med1);
}

getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 45


OUTPUT

enter the no. of elements:6

enter the elements: 9


8
7
6
5
4

the elements after sorting are :4,5,6,7,8,9

upper medians 7 and lower medians 6

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 46


PROGRAM 17

// WAP to implement Depth First Search algorithm

# include<stdio.h>
# define size 20
# define T 1
# define F 0

struct Edge
{
int terminal;
struct Edge *next;
};
struct Vertex
{
int visit;
int vertex_no;
char info;
int path_length;
struct Edge *Edge_Ptr;
};
void Table(int , int matrix [size][size], struct Vertex
vert[size]);
struct Edge *Insert_Vertex (int , struct Edge *);
void DFS ( int , int *dist, struct Vertex vert [size]);
void Input(int, int a [size][size]);
void Output(int, int a [size][size]);

struct Edge * Insert_Vertex (int vertex_no, struct Edge


*first)
{
struct Edge *new1, *current;
new1 = (struct Edge *) malloc(sizeof(struct
Edge));
new1->terminal = vertex_no;
new1->next = NULL;
if (!first)
return (new1);

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 47


for (current = first; current->next; current =
current->next);
current->next = new1;
return (first);
}

/* Initializing entries */

void Table(int vertex_num, int matrix [size][size],


struct Vertex vert[size])
{
int i, j;
for (i = 0; i < vertex_num; i++)
{
vert [i].visit = F;
vert [i].vertex_no = i+1;
vert [i].info = 'A'+ i;
vert [i].path_length = 0;
vert [i].Edge_Ptr = NULL;
}

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


for (j =0; j < vertex_num ; j++)
if (matrix [i][j] > 0)
vert [i].Edge_Ptr = Insert_Vertex (j,
vert [i].Edge_Ptr);
}

/* Computing path length */


void DFS ( int index, int *dist,
struct Vertex vert [size])
{
struct Edge *Link;
vert [index].visit = T;
vert [index].path_length = *dist;
*dist += 1;
for ( Link = vert [index].Edge_Ptr; Link; Link =
Link->next)
if (vert [Link->terminal].visit == F)
DFS (Link->terminal, dist, vert);
}

/* Input function to read adjacency matrix */

void Input(int number, int a [size][size])


{
int i, j;

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 48


printf("\n Input the adjacency matrix \n");

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


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

/* Output function */
void Output(int number, int a [size][size])
{
int i, j;
printf("\n Adjacency matrix \n");
for (i = 0; i < number; i++)
{
for (j = 0; j < number; j ++)
{
printf(" %d", a [i][j]);
}
printf("\n");
}
}

/* Function main */
void main()
{
int i;
int number, index, dist;
int a [size][size];
struct Vertex vert [size];
struct Edge *List;
printf("\n Input the number of vertices in the
graph: ");
scanf("%d", &number);
Input(number, a);
Output(number, a);

Table(number, a, vert);
printf("\n Input the starting vertex 0- %d:",
number-1);
scanf("%d", &index);
dist = 0;
DFS (index, &dist, vert);

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 49


printf("\n Path length of the vertex from %c",
vert[index].info);
printf("\n Vertex Length Vertex Connectivity \n
");
for (i = 0; i < number; i++)
{
printf("\n %c %d ", vert[i].info,
vert[i].path_length);
for (List= vert[i].Edge_Ptr; List; List = List-
>next)
{
printf(" ");
putchar(List->terminal+'A');
}
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 50


OUTPUT

Input the number of vertices in the graph: 3

Input the adjacency matrix


1
2
1

3
2
3

4
5
4

Adjacency matrix
1 2 1
3 2 3
4 5 4

Input the starting vertex 0- 2:1

Path length of the vertex from B


Vertex Length Vertex Connectivity

A 1 A B C
B 0 A B C
C 2 A B C

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 51


PROGRAM 18

// WAP to implement Breadth First Search algorithm

# include<stdio.h>
# define size 20
# define T 1
# define F 0

struct Edge
{
int terminal;
struct Edge *next;
};

struct Vertex
{
int visit;
int vertex_no;
char info;
int path_length;
struct Edge *Edge_Ptr;
};
struct Q
{
int info;
struct Q *next;
};

void Table(int , int matrix [size][size], struct Vertex


vert[size]);
struct Edge *Insert_Vertex (int , struct Edge *);
void BFS ( int , struct Vertex vert [size]);
void Input(int, int mat [size][size]);
void Output(int number, int mat [size][size]);
struct Q *Insert_Queue(int vertex_no, struct Q *first);
struct Q *Delete_Queue(int *vertex_no, struct Q *first);

/* Insert vertex into connectivity list */

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 52


struct Edge * Insert_Vertex (int vertex_no, struct Edge
*first) {
struct Edge *new1, *current;
new1 = (struct Edge *) malloc(sizeof(struct
Edge));
new1->terminal = vertex_no;
new1->next = NULL;
if (!first)
return (new1);
for (current = first; current->next; current =
current->next);
current->next = new1;
return (first);
}

/* Insert vertices into queue */

struct Q * Insert_Queue(int vertex_no, struct Q *first)


{
struct Q *new1, *current;
new1 =(struct Q *) malloc(sizeof(struct Q));
new1->info = vertex_no;
new1->next = NULL;
if (!first)
return (new1);
for (current = first; current->next; current =
current->next);
current->next = new1;
return (first);
}

struct Q * Delete_Queue(int *vertex_no, struct Q *first)


{
struct Q *previous;
if (!first)
return (NULL);
*vertex_no = first->info;
previous = first;
first = first->next;
free(previous);
return (first);
}

/* Initializing entries */

void Table(int vertex_num, int matrix [size][size],

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 53


struct Vertex vert[size])
{
int i, j;
for (i = 0; i < vertex_num; i++)
{
vert [i].visit = F;
vert [i].vertex_no = i+1;
vert [i].info = 'A'+ i;
vert [i].path_length = 0;
vert [i].Edge_Ptr = NULL;
}

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


for (j =0; j < vertex_num ; j++)
if (matrix [i][j] > 0 )
vert [i].Edge_Ptr = Insert_Vertex (j,
vert [i].Edge_Ptr);
}

/* Computing path length */

void BFS ( int index, struct Vertex vert [size])


{
struct Q *queue = NULL;
struct Edge *Link;
vert [index].visit = T;
queue = Insert_Queue(index, queue);
while(queue)
{
queue = Delete_Queue(&index, queue);
for ( Link = vert [index].Edge_Ptr; Link; Link =
Link->next)
{
if (vert [Link->terminal].visit == F)
{
vert[Link->terminal].visit = T;
vert[Link-
>terminal].path_length=vert[index].path_length+1;
queue = Insert_Queue(Link->terminal,
queue);
}
}
}
}

/* Input function to read adjacency matrix */

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 54


void Input(int number, int mat [size][size])
{
int i, j;
printf("\n Input the adjacency matrix \n");
for (i =0; i < number; i++)
{
for (j=0; j < number; j ++)
{
scanf("%d", &mat [i][j]);
}
printf("\n");
}
}

/* Output function to display adjacency matrix */

void Output(int number, int mat [size][size])


{
int i, j;
printf("\n Adjacency matrix \n");
for (i =0; i < number; i++)
{
for (j=0; j < number; j ++)
{
printf(" %d", mat [i][j]);
}
printf("\n");
}
}

/* Function main */
void main()
{
int i, number, index;
int mat [size][size];
struct Vertex vert [size];
struct Edge *List;
printf("\n Input the number of vertices in the
graph: ");
scanf("%d", &number);
Input(number, mat);
Output(number, mat);
Table(number, mat, vert);
printf("\n Input the starting vertex 0-
%d :",number-1);
scanf("%d", &index);
BFS (index, vert);

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 55


printf("\n Path length of the vertex from %c",
vert[index].info)
;
printf("\n Vertex Length Vertex Connectivity \n
");
for (i = 0; i < number; i++)
{
printf("\n %c %d ",vert[i].info,
vert[i].path_length);
for (List= vert[i].Edge_Ptr; List; List = List-
>next)
{
printf(" ");
putchar(List->terminal+'A');
}
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 56


OUTPUT

Input the number of vertices in the graph: 3

Input the adjacency matrix


2
3
2

1
2
1

4
5
4

Adjacency matrix
2 3 2
1 2 1
4 5 4

Input the starting vertex 0- 2 :2

Path length of the vertex from C


Vertex Length Vertex Connectivity

A 1 A B C
B 1 A B C
C 0 A B C

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 57


PROGRAM 19

// WAP to implement Bellman – Ford algorithm to find the Shortest Path

#include<stdio.h>
#include<curses.h>
void relax(int d[10],int w[25][25],int p[10],int t);

int main()
{
clrscr();
int n,i,j,wt[25][25],d[10],pi[10],x;
printf(“\n Enter the no. of vertices (0<n<6): “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j)
{
printf(“\nweight[%d][%d]: “,i,j);
scanf(“%d”,&wt[i][j]);
}
}
}
printf(“\n Assume source node is 0th vertex “);
for(x=1;x<n;x++)
{
d[x]=100;
pi[x]=NULL;
}
d[0]=0;
pi[0]=NULL;
relax(d,wt,pi,n);
printf(“\n This is the path followed “);
int getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 58


void relax(int d[10],int w[25][25],int p[10],int t)
{
int m,n,q;
for(q=0;q<2;q++)
{
for(n=0;n<t;n++)
{
for(m=0;m<t;m++)
{
if(n!=m && w[n][m]!=0)
{
if(d[m]>d[n]+w[n][m])
{
d[m]=d[n]+w[n][m];
p[m]=n;
printf(“\np[%d]: %d”,m,p[m]);
}
}
}
}
}
printf(“\n%d”,t-1);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 59


OUTPUT

Enter the no. of vertices (0<n<6): 3

weight[0][1]: 5

weight[0][2]: 7

weight[1][0]: 0

weight[1][2]: -2

weight[2][0]: 0

weight[2][1]: 0

Assume source node is 0th vertex


p[1]:0
p[2]:0
p[2]:1
p[2]:2
This is the path followed

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 60


PROGRAM 20

// WAP to implement Dijkstra Algorithm

# include<stdio.h>

# define size 20
# define P 1
# define T 0
# define infinity 9999

struct Label
{
int predecessor;
int length;
int flag;
};

int k, min, count;


struct Label state[size];
int visit_path[size];

int Short_Path(int a[size][size], int , int , int,


int path [size], int *);
void Input(int , int a[size][size]);
void Output(int , int a[size][size]);

/* Shortest path computing function */


int Short_Path(int a[size][size], int n, int s, int t,
int path[size], int *dist)
{
int i;
int t1, t2;
*dist = 0;

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


{

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 61


state[i].predecessor = 0;
state[i].length = infinity ;
state[i].flag = T;
}
/* Make source vertex permanent */
state[s].predecessor = 0;
state[s].length = 0;
state[s].flag = P;

/* Start from source vertex */

k = s;
do
{
/* Check all the paths from kth vertex and find
their distance from k vertex */
for ( i = 1; i <= n; i++)
{
if ((a[k][i] > 0) && (state[i].flag == T))
{
if ((state[k].length + a[k][i]) <
state[i].length)
{
state[i].predecessor = k;
state[i].length = state[k].length +
a[k][i];
}
}
}
min = infinity;
k = 0;
for ( i =1; i <= n; i++)
{
if ((state[i].flag == T) && (state[i].length
< min))
{
min = state[i].length;
k = i;
}
}
if ( k==0)
return (0);
state[k].flag = P;
} while(k != t);

/* Store optimal path */


k = t;

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 62


count = 1;
do
{

visit_path[count] = k;
count ++;
k = state[k].predecessor;
} while(k!= 0);

/* Reverse the vertices since algorithm stores path in


reverse direction */

count --;
for ( i = 1; i <= count ; i++)
path[i] = visit_path[count-i+1];

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


{
t1 = path[i];
t2 = path [i+1];
*dist += a[t1][t2];
}
return (count);
}

/* Input function */
void Input(int n, int a[size][size])
{
int i, j;
printf("\n Input adjacency matrix \n");
for(i =0; i < n; i++)
{
for(j =0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
printf("\n");
}
}

/* Output function */
void Output(int n, int a[size][size])
{
int i, j;
printf("\n Adjacency matrix \n");
for(i =0; i < n; i++)
{

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 63


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

/* Function main */

void main()
{
int a[size][size];
int path [size];
int org, dest, dist;
int count, i, n;

printf("\n Input the number of vertices in the graph:


");
scanf("%d", &n);

Input(n,a);
Output(n,a);

printf("\n Input strating vertex: ");


scanf("%d", &org);
printf("\n Input destination: ");
scanf("%d", &dest);
count = Short_Path(a, n, org, dest, path, &dist);
if (dist)
{
printf("\n Shortest path: %d", path[1]);
for (i = 2; i<=count; i++);
printf(" => %d", path[i]);
printf("\n Minimum distance = %i", dist);
}
else
printf("\n Path does not exist \n");
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 64


OUTPUT

Input the number of vertices in the graph: 3

Input adjacency matrix


1
2
1

3
2
3

4
5
4

Adjacency matrix
1 2 1
3 2 3
4 5 4

Input strating vertex: 2

Input destination: 3

Path Does not exist

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 65


PROGRAM 21

// WAP to implement Floyd Warshall algorithm

#include<stdio.h>
#include<curses.h>
#include<stdlib.h>
int min(int e,int f);

int main()
{
clrscr();
int n,m,b,c,d,i,j,a[10][10],pi[10][10];
printf(“\n Enter the no. of rows and column: “);
scanf(“%d %d”,&m,&n);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
scanf”%d”,&a[i][j]);
}
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
{
if(i==j |\ a[i][j]>=100)
p[i][j]=0;
else
pi[i][i]=i;
printf(“ %d”,pi[i][j]);
}
}
for(b=1;b<=m;b++)
{
for(c=1;c<=m;c++)
{

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 66


for(d=1;d<=m;d++)
{
if(a[c][d]<=a[c][b]+a[b][d])
pi[c][d]=pi[b][d];
a[c][d]=min(a[c][d],a[c][b]+a[b][d]);
}
}
}
printf(“\n\nThe resultant shortest weight matrix is:
\n\n”);
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
printf(“%d”,a[i][j];
}
printf(“\n\nThe resultant intermediate vertex matrix
is: \n\n”);
for(i=1;i<=m;i++)
{
printf(“\n”);
for(j=1;j<=n;j++)
printf(“%d”,pi[i][j];
}
int getch();
}

int min(int e,int f)


{
return((e<f) ? e : f);
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 67


OUTPUT

Enter the no. of rows and columns: 5 5


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

The resultant shortest weight matrix is:

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

The resultant intermediate vertex matrix is:

0 3 4 5 1
4 0 4 2 1
4 3 0 2 1
4 3 4 0 1
4 3 4 5 0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 68


PROGRAM 22

// WAP To Implement Naive String Matching

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char mstr[20];
char pstr[20];
int n,m;
int s,i,flag=0,j;
cout<<"\n\nEnter Main String : ";
cin>>mstr;
cout<<"\n\nEnter Pattern String : ";
cin>>pstr;
n=strlen(mstr);
m=strlen(pstr);
for(s=0;s<=(n-m);s++)
{
flag=0;
j=0;
while(!flag && (j<m))
{
if(pstr[j]!=mstr[j+s])
flag=1;
else
j++;

}
if(!flag)
cout<<"\nPattern Exists With
Shift :"<<s<<"\n";

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 69


OUTPUT

Enter Main String : abaabba

Enter Pattern String : aba

Pattern Exists With Shift :0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 70


PROGRAM 23

// WAP To Implement Rabin Karp String Matching

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<math.h>
#include<conio.h>
void main()
{
clrscr();

double mstr;
int pstr;
int j;
cout<<"\nEnter Main Text : ";
cin>>mstr;
cout<<"\nEnter Pattern Text : ";
cin>>pstr;
int p=pstr % 13;
int q=0;
//To Know The No. Of Digits In Pattern Text
int n=pstr;
int dp=0;
while(n)
{
n=n/10;
dp++;
}
//This Logic Ends Here
//To Know The No. Of Digits In Main Text
int m=mstr;
int dm=0;
while(m)
{
m=m/10;
dm++;
}
//This Logic Ends Here

int s=0;
double marray[20],parray[20];
m=mstr;n=pstr;
int d,i;

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 71


for(i=dm;i>=0;i--)
{
d=m % 10;
marray[i]=d;
m=m / 10;
}
for(i=dp;i>=0;i--)
{
d=n % 10;
parray[i]=d;
n=n / 10;
}

for(s=1;s<=(dm-dp+1);s++)
{
i=dp+s-1;
j=0;
n=0;
while(i>=s)
{
n=n+(pow(10,j)*marray[i]);
i--;
j++;
}
q=int(n) % 13;
if(q==p) //checking the case of spurious hit
{
int flag=0;
int k=1;
while(!flag && (k<=dp))
{
if(parray[k]!=marray[k+s-1])
flag=1;
else
k++;

}
if(!flag)
cout<<"\nPattern Exists With Shift :"<<s-1<<"\n";

}
}
getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 72


OUTPUT

Enter Main Text : abaaba

Enter Pattern Text : aba

Pattern Exists With Shift :0

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 73


PROGRAM 24

// Program for Nqueens Problem

#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<math.h>
#include<stdlib.h>
void main()
{
int *x;
int n;
void NQueens(int *,int,int);
clrscr();
cout<<"\n\tHow many Queens you want to place\n";
cin>>n;
x=(int *)malloc(n+1);
for(int i=0;i<n;i++)
x[i]=0;
cout<<"\n\tThe solution Matrix is :- \n\t";
NQueens(x,1,n);
getch();
}

int place(int *x,int k,int i)


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

void NQueens(int *x,int k,int n)


{
for(int i=1;i<=n;i++)
{
if(place(x,k,i))
{
x[k]=i;
if(k==n)

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 74


{
for(int j=1;j<=n;j++)
cout<<x[j]<<" ";
cout<<"\n\t";
}
else
NQueens(x,k+1,n);
}
}
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 75


PROGRAM 25

// Program to find minimum cost spanning tree using prims algorithm

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#define INFINITY 10000
void main()
{

clrscr();
int n,i,j,k,l,p,mincost,min;
cout<<"\n Enter no. of nodes: ";
cin>>n;
int **cost=new int*[n];
int *closest=new int[n];
int *mstree[2];
for(i=0;i<n;i++)
*(cost+i)=new int[n];
for(i=0;i<2;i++)
*(mstree+i)=new int[n-1];
cout<<"\n Assuming there are no self loops and the
graph is undirected";
cout<<"\n Enter cost matrix(0 for no path)........\n";
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{ if(i==j)
cost[i][j]=INFINITY;
else
{
cout<<"\n Weight of edge between Node "<<i+1<<"
&Node "<<j+1<<" : ";
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=INFINITY;
cost[j][i]=cost[i][j];

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 76


}
}

//Find minimum cost edge


mincost=cost[0][0];
k=l=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
if(cost[i][j]<mincost)
{
mincost=cost[i][j];
k=i;
l=j;
}
}

mstree[0][0]=k;
mstree[0][1]=l;
// Initialize closest

for(i=0;i<n;i++)
if(cost[i][l]<cost[i][k])
closest[i]=l;
else
closest[i]=k;

closest[k]=closest[l]=-1;
for(i=1;i<(n-1);i++)
{
//find remaining n-2 edges of spanning tree
p=0;j=0;
while(closest[p]==-1)p++;
min=cost[p][closest[p]];
j=p;
for(;p<n;p++)
if(closest[p]!=-1 && cost[p][closest[p]]<min)
{
j=p;
min=cost[p][closest[p]];
}
mstree[i][0]=j;
mstree[i][1]=closest[j];
mincost+=cost[j][closest[j]];
closest[j]=-1;

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 77


for(k=0;k<n;k++)
if(closest[k]!=-1 && (cost[k]
[closest[k]]>cost[k][j]))
closest[k]=j;
}
cout<<"\n Minimum Cost= "<<mincost;

delete cost;
delete closest;

getch();
}

Gulsheen Kaur IT-1 Algorithm Design & Analysis Page no: 78

Das könnte Ihnen auch gefallen