0% found this document useful (0 votes)
80 views60 pages

DAA Record

The document outlines an algorithm for solving the knapsack problem using a greedy approach. It includes code for sorting items by the ratio of their profit to weight in descending order and iteratively selecting the most valuable items until the knapsack capacity is reached to maximize total profit.

Uploaded by

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

DAA Record

The document outlines an algorithm for solving the knapsack problem using a greedy approach. It includes code for sorting items by the ratio of their profit to weight in descending order and iteratively selecting the most valuable items until the knapsack capacity is reached to maximize total profit.

Uploaded by

Ax
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

TABLE OF CONTENTS

Page Mark Staff


S.No Date Title of the Exercises
no. s signature
1 BINARY SEARCH – DIVIDE AND CONQUER

2 MAXIMUM AND MINIMUM – DIVIDE AND CONQUER

3 KNAPSACK PROBLEM- GREEDY TECHNIQUE

4a MINIMUM SPANNING TREE – PRIMS ALGORITHM

4b MINIMUM SPANNING TREE – KRUSKAL’S ALGORITHM

5 SINGLE SOURCE SHORTEST PATH – DJISTRA’S ALGORITHM

6 MULTISTAGE GRAPHS – DYNAMIC PROGRAMMING

7 ALL PAIR SHORTEST PATH – DYNAMIC PROGRAMMING

TRAVELING SALESMAN PROBLEM – DYNAMIC


8 PROGRAMMING

9 N QUEENS PROBLEM – BACKTRACKING APPROACH

10 SUM OF SUBSETS – BACKTRACKING APPROACH

11 0/1 KNAPSACK PROBLEM – BRANCH AND BOUND

12 TRAVELING SALESMAN PROBLEM – BRANCH AND BOUND

EX NO : 1 BINARY SEARCH – DIVIDE AND CONQUER DATE:


AIM:

To Write a C program for Performing Binary Search Operation using Divide and
Conquer Approach.

ALGORITHM:
//PROGRAM FOR BINARY SEARCH:-

#include<stdio.h>

int binary_search(int [], int, int, int); //Declaration of Recursive Function "binary()"

int a[20],i,low,high,c=0,mid,n,search;//Declaration of Needed Variable

int main()

printf("\n\t\t\t RECURSIVE BINARY SEARCH");

printf("\nENTER THE NUMBER OF ELEMENT IN THE LIST....");

scanf("%d",&n); //Getting the Number of element

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

printf("\nENTER THE %d ELEMENT....",i);

scanf("%d",&a[i]); //Getting Array elements

printf("\nENTER THE SEARCH ELEMENT...."); //Getting the Search element

scanf("%d", &search);

low=1;high=n; //Assigning the first and last element of array to low and high

binary_search(a,low,high,search); //Recursive function calling

if(c==0)

{ printf("\nTHE ELEMENT IS NOT FOUND");

return 0;

int binary_search(int a[],int low,int high,int search) //Recursive Function Definition

if(low==high) //The Problem is small

if(search==a[low])
{

printf("\nTHE ELEMENT PRESENT IN....%d",low);

exit(0);

else

printf("\nTHE ELEMENT NOT FOUND IN LIST");

exit(0);

if(low<=high) //The problem is large

mid=(low+high)/2; //Finding the mid position

if (a[mid]==search) //If search element is equal to mid element

printf("\nTHE ELEMENT PRESENT IN....%d",mid);

c++;

exit(0);

else if(a[mid]>search) //if search element less than mid element

binary_search(a,low, mid-1,search); //Sub Recursive call

else if(a[mid]<search) //if search element greater than mid element

binary_search(a,mid+1,high,search); //Sub Recursive call

}
}

OUTPUT:

CRITERIA MAXIMUM MARKS MARKS OBTAINED


10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Binary Search Operation using Divide
and Conquer Approach was executed successfully.

EX NO : 2 MAXIMUM AND MINIMUM – DIVIDE AND CONQUER DATE:


AIM:

To Write a C program for Performing Maximum and Minimum Operation using


Divide and Conquer Approach.

ALGORITHM:

//PROGRAM FOR RECURSIVE MAX AND MIN:-


#include<stdio.h>

int maxmin(int,int,int*,int*);//RECURSIVE FUNCTION DECLARATION

int a[10],i,n,low=0,high=0,j=0,mid,max,min;//DECLARATION FOR REQUIRED VARIABLE

int main()

printf("\t\t\tRECURSIVE MAXIMUM MINIMUM");

printf("\nENTER THE NUMBER OF ELEMENTS...");

scanf("%d",&n); //GETTING n NUMBER OF VALUE

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

printf("\nENTER THE %d ELEMENTS...",i);

scanf("%d",&a[i]); //GETTING THE ARRAY ELEMENTSs

low=0;high=n-1; //ASSIGNING THE LAST AND FIRST INDEX POSITION TO LOW AND HIGH

maxmin(low,high,&max,&min);//CALLING RECURSIVE FUNCTION

printf("\nTHE MAXIMUM VALUE IS...%d",max);

printf("\nTHE MINIMUM VALUE IS...%d",min);

return 0;

int maxmin(int low,int high,int *max,int *min)//RECURSIVE FUNCTION DEFINITION

int rmax,rmin,lmax,lmin;//DECLARATION OF REQUIRED VARIABLE

if(low==high)//CHECKING WHETHER ONLY ONE ELEMENT IS PRESENT

*max=a[low];

*min=a[high];

else if(low==(high-1))//ELEMENT PRESENT MORE THAN ONE

if(a[low]>a[high])//COMPARING THE ELEMENT IN LOW AND HIGH INDEX POSITION

*max=a[low];
*min=a[high];

else

*max=a[high];

*min=a[low];

else

mid=(low+high)/2; //FINDING MID VALUE

maxmin(low,mid,&lmax,&lmin); //RECURSIVE CALL FOR ELEMENT BEFORE MID VALUE

maxmin(mid+1,high,&rmax,&rmin);//RECURSIVE CALL FOR ELEMENT AFTER MID VALUE

//COMBINING THE DIVIDED SETS TWO SETS

if(lmax<rmax) //COMPARING THE MAX VALUE OF TWO SETS

*max=rmax;

else

*max=lmax;

if(lmin<rmin) //COMPARING THE MIN VALUE OF TWO SETS

*min=lmin;

else

*min=rmin;

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Maximum and Minimum Operation
using Divide and Conquer Approach was executed successfully

EX NO : 3 KNAPSACK PROBLEM- GREEDY TECHNIQUE DATE:


AIM:

To Write a C program for Performing Knapsack Problem using Greedy Approach.

ALGORITHM:

SOURCE CODE FOR KNAPSACK PROBLEM:


#include<stdio.h>

int knapsack(int,int);//Declaration of function knapsack

float p[10],w[10]; //Declaration of variable for profit and weight

float x[10],r[10];

int main()

int n,j,i,temp,temp1,temp3;

float max;

printf("\n\t\t\t\tKNAPSACK PROBLEM");

printf("\nENTER THE TOTAL NUMBER OF WEIGHT...");

scanf("%d",&n); //Number of weight

printf("ENTER THE KNAPSACK CAPACITY...");

scanf("%f",&max); //Size of knapsack

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

printf("ENTER THE %d WEIGHT...",i);

scanf("%f",&w[i]); //Getting the Weight to be Inserted in Knapsack

printf("ENTER THE %d PROFIT...",i);

scanf("%f",&p[i]); //Getting the Profit of weight

printf("\n");

printf("\tWEIGHT \tPROFIT");

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

printf("\nW%d %.1f \t P%d %.1f",i,w[i],i,p[i]);

//Displaying the weight at its profit before sorting

printf("\n");

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

r[i]=p[i]/w[i]; //Calculating the ratio of Weight and Profit

printf("\nPROFIT %d / WEIGHT %d... %f",i,i,r[i]);


}

for(j=1;j<=n;j++)//Using the bubble sort for sorting profit and weight

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

if(r[i]<r[i+1]) //Checking the ratio for sorting

temp=w[i];

w[i]=w[i+1]; //Swapping the weight

w[i+1]=temp;

temp1=p[i];

p[i]=p[i+1]; //Swappping the profit

p[i+1]=temp1;

temp3=r[i];

r[i]=r[i+1]; //Swapping the ratio of profit and weight

r[i+1]=temp3;

printf("\n________________________________________________________________________________");

printf("\nBASED ON RATION OF PROFIT AND WEIGHT");

printf("\nTHE GIVEN SET OF INPUT IS REARRANGED AS FOLLOW");

printf("\n________________________________________________________________________________");

printf("\n");

printf("\tWEIGHT \tPROFIT");

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

printf("\nW%d %.1f \t P%d %.1f",i,w[i],i,p[i]);

// Printing after the Sorting

}
knapsack(max,n);//Calling knapsack function

int knapsack(int max,int n)//Function Definition of knapsack

int i;

float profit,cu,p1[10];

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

x[i]=0;

cu=max;

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

if(w[i]>cu)

break;

else

x[i]=1;

cu=cu-w[i];

if(i<=n)

x[i]=(cu/w[i]);

profit=0.0;

printf("\n");

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

p1[i]=p[i]*x[i];
printf("\nPROFIT FROM W%d : %f",i,p1[i]);

printf("\n");

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

{ profit=profit+p1[i];

printf("\nTHE OPTIMA SOLUTION IS....%.1f",profit);

OUTPUT:

CRITERIA MAXIMUM MARKS MARKS OBTAINED


10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Knapsack Problem using Greedy
Approach was executed successfully.

EX NO : 4A MINIMUM SPANNING TREE – PRIMS ALGORITHM DATE:


AIM:

To Write a C program for Performing Minimum spanning Tree- Prim’s Algorithm


using Greedy Approach.

ALGORITHM:

SOURCE CODE FOR PRIMS PROGRAM:


#include<cstdio>

using namespace std;

#define x 9999 //ASSINGING X AS INFINITY (i.e) MAX VALUE

int cost[10][10],ner[10],t[10][2];//INITIALIZING THE NEEDED VARIABLES FOR REPRESENTING THE


GRAPH

int main()

int i,j,k,l,v,c,n,min,mincost;////INITIALIZING THE NEEDED VARIABLES

printf("\n\t\t\t\tPRIMS PROGRAM");

printf("\nENTER NUMBER OF EDGES...:");

scanf("%d",&n); //GETTING THE NUMBER OF EDGES

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

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

cost[i][j]=x; //INITIALLY ASSIGN ALL EDGE COST AS MAXIMUM VALUE

printf("\nENTER THE ADJACENCY MATRIX....");

printf("\nIF THERE IS NO EDGE ENTER VALUE AS 9999\n");

min=x; //INITIALLY ASSIGNING MIN VALUE AS MAXIMUM VALUE A=9999

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

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

printf("ENTER THE COST OF %d->%d EDGE...",i,j);

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

//GETTING THE EDGE COST FROM THE USER IF EDGE IS PRESENT

cost[j][i]=cost[i][j];

if(cost[i][j]<min)

// BY COMPARING ALL THE EDGE COST AND FIND OUT THE MINIMUM EDGE COST

min=cost[i][j];
k=i;

l=j;

mincost=cost[k][l];// ASSIGN THE MINIMUM EDGE COST VALUE TO THE VARIABLE MINCOST

t[1][1]=k;//TRAVEL PATH OF SPANNING TREE CONNECTING VERTICES

t[1][2]=l;//TRAVEL PATH OF SPANNING TREE CONNECTING VERTICES

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

if(cost[i][l]<cost[i][k])

ner[i]=l;//INITIALIZE NEAR BASED ON THE FIRST ADDED EDGE

else

ner[i]=k;////INITIALIZE NEAR BASED ON THE FIRST ADDED EDGE

ner[k]=ner[l]=0;

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

min=x;

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

if(ner[k]!=0)

if(cost[k][ner[k]]<min)

//FINDING THE NEXT MINIMUM EDGE BASED ON NEAR VALUE AND MIN VALUE

min=cost[k][ner[k]];// MIN VALUE GETS UPDATED

j=k;
}

t[i][1]=j;//UPDATION OF TRAVEL PATH

t[i][2]=ner[j];//UPDATION OF TRAVEL PATH

mincost+=cost[j][ner[j]];//UPDATION OF MINCOST

ner[j]=0;

for(k=1;k<=n;k++)//UPDATION OF NEAR

if((ner[k]!=0)&&(cost[k][ner[k]]>cost[k][j]))

ner[k]=j;

printf("\nTHE EDGES IN THE MINIMUM COST SPANNING TREE...\n");

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

printf("%d->%d ",t[i][1],t[i][2]);

// PRINTING THE TRAVEL PATH OF MINIMUM SPANNING TREE

printf("\nTHE MINIMUM COST IS...%d",mincost);

// PRINTING THE MINIMUM COST OF MINIMUM SPANNING TREE

return 0;

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Minimum spanning Tree- Prim’s
Algorithm using Greedy Approach was executed successfully.

EX NO : 4B MINIMUM SPANNING TREE – KRUSKAL’S ALGORITHM DATE:


AIM:

To Write a C program for Performing Minimum spanning Tree- Kruskal’s


Algorithm using Greedy Approach.

ALGORITHM:

SOURCE CODE FOR KRUSKAL PROGRAM:


#include<cstdio>

using namespace std;//DECLARATION OF HEADER FILES

void union1(int,int);//DECLARATION OF FUNCTIONS FOR ADDING EDGES ONE BY ONE

int find1(int);

int parent[100];

int find1(int i)//FINDING ALREADY HAVING PARENT OR NOT

while(parent[i]>=0)

i=parent[i];

return(i);

void union1(int x1,int x2)// FUNCTION OF ADDING VERTEX ONE BY ONE

parent[x1]=x2;

int main()

int a[20][20],y[20],t[20][20],z[20],x[20];// DECLARATION OF NEEDED VARIABLES AND


ARRAYS

int mincost,n1,r,te,n,u,v,i,j,k;

printf("\n\t\t\t\tKRUSKAL PROGRAM");

printf("\nENTER THE NUMBER OF NODES...");

scanf("\n%d",&n);//GETTING NUMBER OF NODES

printf("\nENTER THE COST OF ADJACENCY MATRIX...");

printf("\nNOTE....IF NO EDGE EXIST ENTER 9999\n");

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

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

a[i][j]=9999;//INITIAL ASSIGNMENT OF ALL VALUES TO 9999

}
}

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

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

printf("a[%d][%d]=",i,j);

scanf("%d",&a[i][j]);// GETTING THE COST OF EACH AND EVERY EDGE

a[j][i]=a[i][j];

//PICKING MINIMUM COST EDGE ONE BY ONE ANDREARRANGING THE THE DATA BASED ON
MINIMUM VALUE

k=1;

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

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

if((i<j)&&(a[i][j]!=9999))

x[k]=i;

y[k]=j;

z[k]=a[i][j];

k++;

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

for(j=1;j<k;j++)

if(i<j)

if(z[i]>z[j])
{

te=z[i];

z[i]=z[j];

z[j]=te;

te=x[i];

x[i]=x[j];

x[j]=te;

te=y[i];

y[i]=y[j];

y[j]=te;

n1=k-1;

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

parent[i]=-1;

r=1;

mincost=0;//ASSIGNING MIN COST VALUE TO ZERO

i=0;

while((i<n-1)&&(r!=n1))// CHECKING FOR HEAP NOT EMPTY CONDITION

u=x[r];

v=y[r];

j=find1(u);

k=find1(v);

if(j!=k)

i=i+1;
t[i][1]=u;//UPDATION OF TRAVEL PATH

t[i][2]=v;//UPDATION OF TRAVEL PATH

mincost=mincost+z[r];//UPDATION OF MINIMUM COST

union1(j,k);

r++;

if(i!=n-1)

printf("\nNO SPANNING TREE");

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

printf("\t%d->%d",t[i][1],t[i][2]);//PRINTING FINAL TRAVEL PATH

printf("\nTOTAL COST IS...%d",mincost);// PRINTING MINCOST VALUE

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Minimum spanning Tree- Kruskal’s
Algorithm using Greedy Approach was executed successfully.

EX NO : 5 SINGLE SOURCE SHORTEST PATH – DJISTRA’S ALGORITHM DATE:


AIM:

To Write a C program for Performing Single Source shortest path - Djistra’s


Algorithm using Greedy Approach.

ALGORITHM:

SOURCE CODE FOR DIJKSTRA PROGRAM:


#include<stdio.h> //DECLARATION OF HEADER FILES

#define INFINITY 9999 //Initialize INFINITY value

int n,cost[10][10],dist[10],visit[10],front,rear,v;//Declaration of needed Variables

void Initial(int n)// Function Definition

int i,j;

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

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

cost[i][j] = INFINITY; //Initialize all edge values as infinity

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

dist[i] = INFINITY;//Initialize Assign Infinity for all distance

visit[i] = 0; //Assigning not yet visited any nodes

int nearest()//Function Definition

int i,node, weight;

weight = INFINITY;

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

if(visit[i] == 0 && dist[i] < weight) //Checking for not yet visited node and
distance less than infinity

{
weight = dist[i];

node=i;

return node;

void Dijkstra(int v)//Function Definition

int i,u,q,alt;//Initialize needed variables

dist[v]=0;

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

u=nearest();//Function Call

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

if(cost[u][v] == INFINITY)

continue;

alt = dist[u] + cost[u][v];//Update the distance value

if(alt < dist[v])

dist[v] = alt;

visit[u] = 1;//node visited

void display()//Function Definition


{

int i,j;

printf("\nCOST MATRIX\n");

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

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

printf("%d\t", cost[i][j]);//Display the cost values

printf("\n");

int main()

int i,j,k,m;//Declaration of needed variables

printf("\n\t\t\t\tDIJKSTRA PROGRAM");

printf("\nENTER THE NUMBER OF VERTICES...");

scanf("%d",&n);//Getting n number of values

Initial(n);//Function Call

printf("\nNOTE...IF EDGE DOES NOT EXIST ENTER 9999\n");

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

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

printf("ENTER THE DISTANCE BETWEEN %d AND %d....",i,j);

scanf("%d" ,&cost[i][j]);//Getting the distance value

}
}

display();//Function Call

printf("\nENTER THE SOURCE VERTEX...");

scanf("%d",&v);//Getting the source vertex

Dijkstra(v);//Function Call

printf("\nRESULT...");

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

printf("\nDISTANCE OF %d IS...",i);

printf("%d",dist[i]);//Print the Distance value

printf("\n");

return 0;

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Single Source shortest path - Djistra’s
Algorithm using Greedy Approach was executed successfully.
EX NO : 6 MULTISTAGE GRAPHS – DYNAMIC PROGRAMMING DATE:

AIM:

To Write a C program for Performing Multi stage graph operation using Dynamic
Programming Approach.

ALGORITHM:
SOURCE CODE FOR MULTISTAGE GRAPH:

#include<cstdio> //Declaration of header files

using namespace std;

int main()

int l,edgecost,ed,c[20][20],d[20],p[20],n,k,j,i,r,cost[20];//Declaration of required


variables

printf("\n\t\t\t\tMULTISTAGE GRAPH");

printf("\n\nENTER HOW MANY NODES...");

scanf("%d",&n); //Getting the number of nodes

printf("ENTER HOW MANY STAGES...");

scanf("%d",&k); //Getting the number of stages

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

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

c[i][j]=9999; //Initially Assign Max value to all edges

printf("ENTER HOW MANY EGDES...");

scanf("%d",&ed); //Getting the number of edges

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

printf("ENTER THE %d EDGES AND ITS COST...",i);

scanf("%d %d %d",&j,&r,&edgecost); //Getting the respective edge and its cost

c[j][r]=edgecost;

cost[n]=0; //Intially Assign cost of nth node to zero

for(j=n-1;j>=1;j--)
{

edgecost=9999;

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

if(c[j][i]==9999)

continue;

l=c[j][i]+cost[i]; //Computing the cost of each and every edge based on


minimum value

if(edgecost>l)

edgecost=l;

r=i;

cost[j]=edgecost;

d[j]=r;

p[1]=1;

p[k]=n;

for(j=2;j<k;j++)

p[j]=d[p[j-1]]; //Finding the minimum cost path

printf("\nPATH...");

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

printf(" -> %d",p[i]); //Printing the minimum cost path


}

return 0;

OUTPUT:

CRITERIA MAXIMUM MARKS MARKS OBTAINED


10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Multi stage graph operation using
Dynamic Programming Approach was executed successfully.

EX NO : 7 ALL PAIR SHORTEST PATH – DYNAMIC PROGRAMMING DATE:


AIM:

To Write a C program for Performing All pair shortest path operation using
Dynamic Programming Approach.

ALGORITHM:

SOURCE CODE FOR ALL PAIR SHORTEST PATH:

#include<stdio.h> //Declaration of header files


void allpath(); //Declaration of allpath() function

int cost[20][20],n;

int main()

int i,j;

printf("\t\t\t\tALL PAIR SHORTEST PATH");

printf("\nENTER THE NUMBER OF NODES...");

scanf("%d",&n); //Getting the number of nodes

printf("ETNER THE COST MATRIX...");

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

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

scanf("%d",&cost[i][j]);//Getting the cost of each and every edge

allpath(); //Function call for allpath() function

return 0;

void allpath() //Function definition for allpath() function

int i,j,k,a[20][20];

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

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

a[i][j]=cost[i][j]; //Copying the cost of every edge into A array

}
}

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

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

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

if(a[i][j]<(a[i][k]+a[k][j]))//Checking the minimum cost with respect to intermediate


nodes

a[i][j]=a[i][j];

else

a[i][j]=(a[i][k]+a[k][j]);

printf("STEP...%d\n",k);

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

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

printf("%d",a[i][j]);//Printing the results of each and every step

printf("\n");

}
OUTPUT:

CRITERIA MAXIMUM MARKS MARKS OBTAINED


10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing All pair shortest path operation using
Dynamic Programming Approach was executed successfully.

EX NO : 8 TRAVELING SALESMAN PROBLEM – DYNAMIC PROGRAMMING DATE:

AIM:
To Write a C program for Performing Traveling Salesman Problem using
Dynamic Programming Approach.

ALGORITHM:

SOURCE CODE FOR TRAVELING SALESMAN PROBLEM:

#include<stdio.h>
 
int ary[10][10],completed[10],n,cost=0;
 
void takeInput()
{
int i,j;
 
printf("Enter the number of villages: ");
scanf("%d",&n);
 
printf("\nEnter the Cost Matrix\n");
 
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row: %d\n",i+1);
 
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
 
completed[i]=0;
}
 
printf("\n\nThe cost list is:");
 
for( i=0;i < n;i++)
{
printf("\n");
 
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
}
}
 
void mincost(int city)
{
int i,ncity;
 
completed[city]=1;
 
printf("%d--->",city+1);
ncity=least(city);
 
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
 
return;
}
 
mincost(ncity);
}
 
int least(int c)
{
int i,nc=999;
int min=999,kmin;
 
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
 
if(min!=999)
cost+=kmin;
 
return nc;
}
 
int main()
{
takeInput();
 
printf("\n\nThe Path is:\n");
mincost(0); //passing 0 because starting vertex
 
printf("\n\nMinimum cost is %d\n ",cost);
 
return 0;
}

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus, the above C program for Performing Traveling Salesman Problem using
Dynamic Programming Approach was executed successfully.

EX NO : 9 N QUEENS PROBLEM – BACKTRACKING APPROACH DATE:


AIM:

To Write a C program for Performing N QUEENS operation using Backtracking


Approach.

ALGORITHM:

SOURCE CODE FOR N-QUEEN PROBLEM:


#include<cstdio>

#include<cstdlib> //Declaration of header files

using namespace std;

int nqueen(int);//Function declaration all solution to n-queens problem

int place(int);//Function declaration for doing whether a new queen can be placed or not

int x[20];

int main()

int n;

printf("\n\t\t\t\tNQUEENS PROBLEM\n");

printf("\nENTER THE NUMBER OF QUEENS...");

scanf("%d",&n); //Getting number of queen to be placed

printf("\nTHE SOLUTIONS ARE...");

nqueen(n); //Function call for nqueen()

return 0;

int nqueen(int n) //Function defintion for nqueen()

int k,i;

k=1;

while(k>0)

x[k]=x[k]+1;

while((x[k]<=n)&&(!place(k)))

x[k]=x[k]+1;

if(x[k]<=n)
{

if(k==n)

printf("\n");

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

printf("->%d",x[i]);

printf("\n");

else

k=k+1;

x[k]=0;

else

k=k-1;

int place(int k) //function definition for place()

int i;

for(i=1;i<=k-1;i++)

if((x[i]==x[k])||((abs(x[i]-x[k]))==(abs(i-k))))//Checking for two in same


column or in same diagonal
{

return(0);

return(1);

OUTPUT:

CRITERIA MAXIMUM MARKS MARKS OBTAINED


10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing N QUEENS operation using


Backtracking Approach was executed successfully.

EX NO :10 SUM OF SUBSETS – BACKTRACKING APPROACH DATE:


AIM:

To Write a C program for Performing Sum of Subsets operation using


Backtracking Approach.

ALGORITHM:

SOURCE CODE FOR SUM OF SUBSETS:

#include<cstdio> //Declaration of header files


using namespace std;

intsos(int,int,int);//Function Declaration of sos() function

int w[10],m,x[20];

int main()

intn,i,r=0,k=1,s=0;

printf("\n\t\t\t\tSUM OF SUBSET");

printf("\nENTER THE NUMBER OF VALUE...");

scanf("%d",&n); //Getting the n number of weights

printf("\nENTER THE VALUE...");

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

scanf("%d",&w[i]); //Getting the corresponding weight

printf("\nENTER THE M VALUE...");

scanf("%d",&m); //Getting the capacity

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

r=r+w[i];

sos(s,k,r);//Function call for sos()

intsos(ints,intk,int r) //Function definition for sos()

int j;

x[k]=1;//Generating the left child

if((s+w[k]==m))

printf("\nTHE SOLUTION IS...");

for(j=1;j<=k;j++)
{

printf(" %d",x[j]);//Printing the result

else if((s+w[k]+w[k+1])<=m)

sos((s+w[k]),(k+1),(r-w[k]));//Recursive call for function sos()

if(((s+r-w[k])>=m)&&((s+w[k+1])<=m)) //Generate the right child

x[k]=0;

sos(s,k+1,(r-w[k]));//Recursive call for function sos()

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Sum of Subsets operation using
Backtracking Approach was executed successfully.

EX NO : 11 0/1 KNAPSACK PROBLEM – BRANCH AND BOUND DATE:


AIM:

To Write a C program for Performing 0/1 Knapsack Problem using Branch and
Bound Programming Approach.

ALGORITHM:

SOURCE CODE FOR 0/1 KNAPSACK PROBLEM:

#include<stdio.h>
int max(int a, int b) {

if(a>b){

return a;

} else {

return b;

int knapsack(int W, int wt[], int val[], int n) {

int i, w;

int knap[n+1][W+1];

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

for (w = 0; w <= W; w++) {

if (i==0 || w==0)

knap[i][w] = 0;

else if (wt[i-1] <= w)

knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);

else

knap[i][w] = knap[i-1][w];

return knap[n][W];

int main() {

int n;

printf("Number of items : ");

scanf("%d",&n);

int val[20];

int wt[20];
int W ;

printf("Profit of items : \n");

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

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

printf("Weight of items : \n");

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

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

printf("Capacity of knapsack : \n");

scanf("%d",&W);

printf("The maximum profit is : %d", knapsack(W, wt, val, n));

return 0;

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing 0/1 Knapsack Problem using Branch
and Bound Approach was executed successfully.

EX NO : 12 TRAVELING SALESMAN PROBLEM – BRANCH AND BOUND DATE:


AIM:

To Write a C program for Performing Traveling Salesman Problem using Branch


and Bound Approach.

ALGORITHM:

SOURCE CODE FOR TRAVELING SALESMAN PROBLEM:

#include<stdio.h>
int a[10][10],visited[10],n,cost=0;

void get()

int i,j;

printf("Enter No. of Cities: ");

scanf("%d",&n);

printf("\nEnter Cost Matrix: \n");

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

printf("\n Enter Elements of Row # : %d\n",i+1);

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

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

visited[i]=0;

printf("\n\nThe cost list is:\n\n");

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

printf("\n\n");

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

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

void mincost(int city)

int i,ncity;

visited[city]=1;
printf("%d ->",city+1);

ncity=least(city);

if(ncity==999)

ncity=0;

printf("%d",ncity+1);

cost+=a[city][ncity];

return;

mincost(ncity);

int least(int c)

int i,nc=999;

int min=999,kmin;

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

if((a[c][i]!=0)&&(visited[i]==0))

if(a[c][i]<min)

min=a[i][0]+a[c][i];

kmin=a[c][i];

nc=i;

if(min!=999)

cost+=kmin;

return nc;
}

void put()

printf("\n\nMinimum cost:");

printf("%d",cost);

void main()

get();

printf("\n\nThe Path is:\n\n");

mincost(0);

put();

OUTPUT:
CRITERIA MAXIMUM MARKS MARKS OBTAINED
10
PROGRAM AND EXECUTION
5
OUTPUT
10
VIVA
25
Total

RESULT:

Thus the above C program for Performing Traveling Salesman Problem using
Branch and Bound Approach was executed successfully.

You might also like