Vous êtes sur la page 1sur 22

ADVANCED ALGORITHMS

Laboratory Work
1. Design, develop, and run a program in any language to implement the Bellman-Ford
algorithm and determine its performance.
2. Design, develop, and run a program in any language to implement Johnsons algorithm
and determine its performance.
3. Design, develop, and run a program in any language to implement a Monte Carlo
algorithm to test the primality of a given integer and determine its performance.
4. Design, develop, and run a program in any language to solve the string matching
problem using nave approach and the KMP algorithm and compare their performances.
5. Design, develop, and run a program in any language to solve modular linear equations.
6. Design, develop, and run a program in any language to implement the FFT algorithm
efficiently.
/*Program to Implement the Bellman-Ford algorithm */
#include <stdio.h>
#include <conio.h>
#define INFINITY 1000
#define SIZE 100
#define TRUE 1
#define FALSE 0
typedef struct {
int u, v, w ;
} Edge;
Edge edges[SIZE];
int e,n,d[SIZE],pre[SIZE],temp[SIZE];
void initialise(int s)
{ int i;
for (i = 0; i < n; ++i)
{ d[i] = INFINITY;
pre[i]=0;
}
d[s] = 0;
}
void relax()
{ int i,j ;
for (i = 1; i <= n-1 ; ++i)
{ for (j = 0; j < e; ++j)
{ if (d[edges[j].u] + edges[j].w < d[edges[j].v])
{ d[edges[j].v] = d[edges[j].u] + edges[j].w;
pre[edges[j].v]= edges[j].u;
}
}
}
}
int check()
{ int i;
for(i=0;i<e;++i)
{ if (d[edges[i].u] + edges[i].w < d[edges[i].v])
return FALSE;
}
return TRUE;
}
void printDist() {
int i,j;
temp[0]=n-1;
j=n-1;
for(i=1; i<n-1; ++i)
{
temp[i]=pre[j];
j=temp[i];
}
for (i = 0; i < n; ++i)
{
printf("\nDISTANCE and PATH to Node%d:\n",i+1);
printf("Distance:%d\n",d[i]);
printf("Path: " );
for(j=n-1; temp[j]!=i && j >=0; --j)
printf("%d->",temp[j]+1);
printf("%d\n",temp[j]+1);
}
// for(i=0;i<e;i++)
// printf("%d",pre[i]);
}
void bellman_ford(int s)
{ int temp;
initialise(s);
relax();
temp=check();
if(temp==TRUE)
printDist();
else
printf("The Graph contains negative cycle");
}
int main( )
{
int i, j, s;
int w,matrix[10][10];
clrscr();
do
{
printf("Enter the no. of VERTICES:\n");
scanf("%d",&n);
if(n<1)
printf("A graph should have atleast one VERTEX");
}while(n<1);
printf("\nEnter the ADJACENCY MATRIX of the GRAPH:\n");
for(i=0;i<n;++i)
{ for(j=0;j<n;++j)
scanf("%d",&matrix[i][j]);
}
printf("\nEnter the SOURCE VERTEX:\n");
scanf("%d",&s);
printf("\n");
e = 0;
for (i = 0; i < n; ++i)
{ for(j =0; j<n ; ++j)
{ if (matrix[i][j] != 0)
{

edges[e].u=i;
edges[e].v = j;
edges[e].w = matrix[i][j];
++e;
}
}
}
bellman_ford(s-1);

getch();
return 0;
}
/* OutPut
Enter the no. of VERTICES:
5
Enter the ADJACENCY MATRIX of the GRAPH:
0 6 0 0 7
0 0 5 -4 8
0 -2 0 0 0
2 0 7 0 0
0 0 -3 9 0
Enter the SOURCE VERTEX:
1
DISTANCE and PATH to Node1:
Distance:0
Path: 1
DISTANCE and PATH to Node2:
Distance:2
Path: 1->1->1->1->5->1
DISTANCE and PATH to Node3:
Distance:4
Path: 1->1->1->1->5->1
DISTANCE and PATH to Node4:
Distance:-2
Path: 1->1->1->1->5->1
DISTANCE and PATH to Node5:
Distance:7
Path: 1->1->1->1->5 */
/* Program to Implement Johnson's Algorithm for Sparse
Graph*/
#include <stdio.h>
#include <conio.h>
#define INFINITY 1000
#define SIZE 100
#define TRUE 1
#define FALSE 0
typedef struct {
int inode, enode;
float weight,nweight ;
} Edge;
Edge edges[SIZE];
int e,eno,pre[SIZE],temp[SIZE],h[SIZE];
int numOfVertices,adjMatrix[10][10],source;
int predecessor[15],distance[15],dist[20][20];
int mark[20];
void johnson();
void initialise(int s)
{ int i;
for (i = 0; i < numOfVertices; ++i)
{ distance[i] = INFINITY;
pre[i]=0;
}
distance[s] = 0;
}
void relax()
{ int i,j ;
for (i = 1; i <= numOfVertices-1 ; ++i)
{ for (j = 0; j < e; ++j)
{ if (distance[edges[j].inode] + edges[j].weight <
distance[edges[j].enode])
{ distance[edges[j].enode] = distance[edges[j].inode] +
edges[j].weight;
pre[edges[j].enode]= edges[j].inode;
}
}
}
}
int bellman_ford(int source)
{ int i,temp;
initialise(source);
relax();
for(i=0;i<e;++i)
{ if (distance[edges[i].inode] + edges[i].weight < distance[edges[i].enode])
return FALSE;
}
return TRUE;
}
void d_initialize(int s)
{ int i;
for( i=0;i<numOfVertices-1;i++)
{
mark[i] =FALSE;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance [s] = 0;
}
int getClosestUnmarkedNode()
{
int minDistance = INFINITY;
int closestUnmarkedNode,i;
for( i=0;i<numOfVertices;i++)
{
if((mark[i]==FALSE) && ( minDistance > distance[i]))
{
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}
void dijkstra(int s)
{
int minDistance = INFINITY;
int closestUnmarkedNode,i;
int count = 0;
d_initialize(s);
while(count < numOfVertices)
{
closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = TRUE;
for( i=0;i<numOfVertices;i++)
{ if((mark[i]==FALSE) && (adjMatrix[closestUnmarkedNode][i]>=0 &&
adjMatrix[closestUnmarkedNode][i]!=INFINITY ) )
{

if(distance[i] > distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]
)

{ distance[i] = distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode]
[i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
for(i=0;i<numOfVertices;i++)
printf("n%d ",distance[i]);
}
void output()
{int i;
for (i=0;i<numOfVertices-1;i++)
printf("d=%d",distance[i]);
}
int main( )
{
int i, j, s;
int w,matrix[10][10];
clrscr();
do
{
printf("Enter the no. of VERTICES:\n");
scanf("%d",&numOfVertices);
if(numOfVertices<1)
printf("A graph should have atleast one VERTEX");
}while(numOfVertices<1);
printf("\nEnter the ADJACENCY MATRIX of the GRAPH:\n");
for(i=0;i<numOfVertices;++i)
{ for(j=0;j<numOfVertices;++j)
scanf("%d",&matrix[i][j]);
}
e = 0;
for (i = 0; i < numOfVertices; ++i)
{ for(j =0; j<numOfVertices ; ++j)
{ if (matrix[i][j] != 0)
{
edges[e].inode=i;
edges[e].enode = j;
edges[e].weight = matrix[i][j];
++e;
}
}
}
eno=e;
johnson();
getch();
return 0;
}
void johnson()
{ int i,j,k,s,temp;
s=numOfVertices;
for(i=0;i<numOfVertices;i++)
{ edges[e].inode=s;
edges[e].enode=i;
edges[e].weight=0;
++e;
}
temp=bellman_ford(s);
if(temp==FALSE)
printf("The Graph contains negative cycle");
else
{
for(i=0;i<=numOfVertices;i++)
h[i]=distance[i];
for(i=0;i<numOfVertices;i++)
printf("\n%d",distance[i]);
for(i=0;i<e;i++)
edges[i].nweight=edges[i].weight + h[edges[i].inode] - h[edges[i].enode];
for(i=0;i<numOfVertices;i++)
{ for(j=0;j < numOfVertices;j++)
{ if(i!=j)
adjMatrix[i][j]=INFINITY;
else
adjMatrix[i][j]=0;
}
}
for(i=0;i<eno;i++)
{ adjMatrix[edges[i].inode][edges[i].enode]=edges[i].nweight;
}
/*for(i=0;i<numOfVertices;i++)
{ for(j=0;j<numOfVertices;j++)
printf("%5d",adjMatrix[i][j]);
printf("%n");
} */
for(i=0;i<numOfVertices;i++)
{
dijkstra(i);
for(j=0;j<numOfVertices ;j++)
{// printf("+%3d",distance[j]);
dist[i][j]= distance[j]+h[j]-h[i];
}
}
for(i=0;i<numOfVertices;i++)
{ for(j=0;j<numOfVertices;j++)
printf("\n%5d",dist[i][j]);
printf("\n");
}
}
}
/*OutPut
Enter the no. of VERTICES:
5
Enter the ADJACENCY MATRIX of the GRAPH:
0 3 8 0 -4
0 0 0 1 7
0 4 0 0 0
2 0 -5 0 0
0 0 0 6 0
0
-1
-5
0
-4
n0 n-2 n-2 n-2 n-4
n2 n0 n0 n0 n-4
n2 n0 n0 n0 n-4
n2 n0 n0 n0 n-4
n5 n3 n3 n3 n0
0 -3 -7 -2 -8
3 0 -4 1 -7
7 4 0 5 -3
2 -1 -5 0 -8
9 6 2 7 0 */
/*Program to implement a Monte Carlo algorithm to test the
primality of a given integer and determine its performance.*/
/*
Program to test primality of an integer by implementing Monte-Carlo algorithm
This program uses Miller-Rabil test for primality
*/

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<math.h>
// Function to compute (a power b)%n
long modExp(long a,long u,long n)
{
long res,init,i;
init=res=a%n;
for(i=1;i<u;i++)
res=(res*init)%n;
return res;
}
/*
witness(a,n): This function returns false if 'a' is a factor of 'n', else it returns
true.
By invoking this function k-times, we can probably guess whether the number
is prime or not
*/
int witness(long a,long n)
{
long t,u,x0,x1;
int i;
t=0,u=n-1;
while(u%2!=1)
t++,u/=2;
printf("t=%ld,u=%ld\n",t,u);

x0=modExp(a,u,n);
printf("x0=%ld\n",x0);
for(i=1;i<=t;i++)
{
x1=(x0*x0)%n;
if(x1==1 && x0!=1 && x0!=n-1)
return 1;
x0=x1;
}
if(x1!=1)
return 1;
return 0;
}
int miller(long n,int s)
{
int j;
long a;

srand(time(NULL));
for(j=1;j<=s;j++)
{
a=0;
while(a==0)
a=rand()%n;
printf("a=%ld,",a);
if(witness(a,n))
return 0; //Definitely not prime
}
return 1; // probably prime
}
void main()
{
long n =0; // holds the number whose primality has to be tested
long a;// holds random number generated in each iteration
int i;
while(n<=2)
{
printf("\nEnter an odd number >2 to check for primality:");
scanf("%ld",&n);
}
if((n%2)==0)
printf("%ld is not prime.\n",n);
else if(miller(n,log(n)))
printf("\n%ld may be prime.",n);
else
printf("\n%ld is not prime.",n);
getch();
}
Output
Enter an odd number >2 to check for primality:617
a=112,t=3,u=77
x0=423
a=77,t=3,u=77
x0=1
a=579,t=3,u=77
x0=194
a=395,t=3,u=77
x0=435
a=167,t=3,u=77
x0=616
a=473,t=3,u=77
x0=423
617 may be prime.
/* Program to implement pattern matching using KMP
algorithm */
// Program to implement Naive string matching
#include<stdio.h>
#include<string.h>
#include<conio.h>
int naive(char * text, char * pat)
{
int m,n,i,j;

n=strlen(text),m=strlen(pat);
if(n<m)
{
printf("\nPattern is longer than text.");
exit(0);
}

for(j=0;j<=n-m;j++)
{
for(i=0;i<m;i++)
{
if(pat[i]!=text[i+j])
break;
}
if(i==m)
return j+1;
}
return 0;
}
void main()
{
char text[50],pat[50];
int pos=0;
puts("\nEnter the text:");
gets(text);
puts("\nEnter the pattern:");
gets(pat);

if(pos=naive(text,pat))
printf("\nPattern found at position %d",pos);
else
printf("\nPattern not found.");
getch();
}
Output
Enter the text:
Hello world
Enter the pattern:
Hello
Pattern found at position 1.
#include<stdio.h>
#include<string.h>
void compuPrefix(char * pat,int *prefix)
{
int i,j,m;

m=strlen(pat);
i=0;
j=prefix[0]=-1;

while (i<m)
{
while (j>-1 && pat[i]!=pat[j])
j=prefix[j];
i++,j++;
if (pat[i] == pat[j])
prefix[i] = prefix[j];
else
prefix[i] = j;
}
}
int KMP(char *text,char * pat)
{
int i,j,prefix[50],n,m;
n=strlen(text);
m=strlen(pat);
/* Preprocessing */
compuPrefix(pat,prefix);
/* Searching */
i=j=0;
while(j<n)
{
while(i>-1 && pat[i]!= text[j])
i=prefix[i];

i++,j++;
if (i>= m)
return(j-i+1);
}
return 0;
}
void main()
{
char text[50],pat[50];
int pos=0;
puts("\nEnter the text:");
gets(text);
puts("\nEnter the pattern:");
gets(pat);

if(pos=KMP(text,pat))
printf("\nPattern found at position %d\n",pos);
else
printf("\nPattern not found.\n");
}
Output
Enter the text:
Amazing India
Enter the pattern:
ndi
Pattern found at position 10
Press any key to continue . . .
Enter the text:
Roger federer
Enter the pattern:
Rojer
Pattern not found.
Press any key to continue . . .
Comparison
Let m be the length of the pattern and n be the length of the text.
Algorithm Preprocessing time Matching time
Nave string matching 0 (No preprocessing) (m(n-m+1))
KMP string matching (m) (n)
/* Program to Implement to solve Modular Linear Equation */

#include<stdio.h>
#include<conio.h>
#include<math.h>
typedef struct
{
int d,x,y;
}Ex;
Ex extended_Euclid(int a, int b)
{
Ex res,resp;
if(b==0)
{
res.d=a;
res.x=1;
res.y=0;
return res;
}
else
{ resp=extended_Euclid(b,a%b);
res.d=resp.d;
res.x=resp.y;
res.y=resp.x-(a/b)*resp.y;
return res;
}
}
void modularlinear(int a,int b,int n)
{ Ex res;
int i;
int x0, result;
res= extended_Euclid(a,n);
printf("\n\nAFTER RUNNING EXTENDED-EUCLID ALGM:\n");
printf("\nD = %d, X = %d, Y = %d",res.d,res.x,res.y);
if (b%res.d==0)
{
x0=res.x*(b/res.d)%n;
// printf("x0 =%d",x0);
if(x0<0)
{if(abs(x0)>n)
x0=2*n+x0;
else
x0=n+x0;
}
printf("\n\n\nTHE SOLUTIONS TO THE MODULAR EQUATION:\n\n");
for(i=0;i<res.d;i++)
{
result=(x0+i*(n/res.d))%n;
printf("Solution%d = %d\n",i+1,result);
}
}
else printf("NO SOLUTIONS");
}
int main()
{
int a,b,x,y,d,n;
clrscr();
printf("Enter the values of \"a\": " );
scanf("%d",&a);
printf("\nEnter the values of \"b\": ");
scanf("%d",&b);
printf("\nEnter the values of \"n\": ");
scanf("%d",&n);
printf("\nThe given MODULAR EQUATION is %dx=%d mod %d\n",a,b,n);
modularlinear(a,b,n);
// printf("X = %d, Y = %d, D = %d\n",res.x,res.y,res.d);
getch();
return 0;
}
/*OutPut
Enter the values of "a": 5
Enter the values of "b": 7
Enter the values of "n": 3
The given MODULAR EQUATION is 5x=7 mod 3
AFTER RUNNING EXTENDED-EUCLID ALGM:
D = 1, X = -1, Y = 2

THE SOLUTIONS TO THE MODULAR EQUATION:

Solution1 = 2 */
/* Program to Implement the EFT Algorithm*/
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <complex.h>
void bit_reverse(complex a[],complex B[],int n)
{ int reverse(int);
int k,m;
for(k=0;k<n;k++)
{ m=reverse(k);
B[m]=a[k];
}
}
int reverse(int num)
{
int i= 2,count=0;
int reverse_num = num;
int num1;
num1=num;
num1 >>= 1;
while(num1)
{
reverse_num <<= 1;
reverse_num |= num1 & 1;
num1 >>= 1;
count++;
}
if ((num%2 == 0)&& count > 0)
{ if ( reverse_num < pow(2,(i+count)))
reverse_num >>= count;
else if (reverse_num > (pow(2,(i+count))+2))
reverse_num >>=(count + i-1);
else
reverse_num >>=(count + i);
}
else if ((num % 2 !=0) && count > 0)
{ if (reverse_num < pow(2,(i+count)))
reverse_num=num << 1;
else
return num ;
}
else
reverse_num <<= i;
return reverse_num;
}
void iterative_FFT(complex a[],int n)
{ int i,j,k,s,res;
double ang,m,cosres,sinres;
complex B[10],w,wm;
bit_reverse(a,B,n);
res=log(n)/log(2);
cout<<"\nAFTER REVERSING THE COEFFICIENTS:\n";
for(i=0;i<n;i++)
{ printf("A%d=",i);
cout<<B[i]<<endl; }
for (s=1;s<=res;s++)
{
m=pow(2,s);
ang=(2*M_PI/m);
wm=complex(cos (ang), sin (ang));
complex t,u;
for(k=0;k<n-1;k+=m){
{ w = complex(1,0);
for(j = 0;j<= m/2 - 1 ;j++)
{ t = w* B[k + j+ m/2];
u = B[k+j];
B[k+j]=u + t;
B[k+j+m/2]=u-t;
ang=(2*M_PI/m);
w=w*complex(cos (ang), sin (ang)); }
}
}
}
cout<<"\n\nTHE DFT OF THE GIVEN POLYNOMIAL IS:\n\n";
for(i=0;i<n;i++)
{ printf("A%d=",i);
cout<<B[i]<<endl; }
}
void main()
{ int i,n;
complex a[10];
clrscr();
cout<<"ITERATIVE-FFT IMPLEMENTATION:\n\n";
cout<<"Enter d number of coefficients:\n";
cin>>n;
cout<<"\nEnter d coefficients:\n";
for(i=0;i<n;i++)
cin>>a[i];
iterative_FFT(a,n);
getch();
}
/*OutPut
ITERATIVE-FFT IMPLEMENTATION:

Enter d number of coefficients:
3

Enter d coefficients:
3 -8 7

AFTER REVERSING THE COEFFICIENTS:
A0=(3, 0)
A1=(1.307109e-79, 1.33848e-126)
A2=(7, 0)
THE DFT OF THE GIVEN POLYNOMIAL IS:
A0=(3, 1.33848e-126)
A1=(3, -1.33848e-126)
A2=(7, 0) */

Vous aimerez peut-être aussi