43
1 SHREE VENKATESHWARA HI-TECH ENGINEERING COLLEGE GOBI-638 455 DEPARTMENT OF INFORMATION TECHNOLOGY LAB MANUAL

Manual DAA-New 1

Embed Size (px)

DESCRIPTION

Manual DAA-New 1 for data analysis and algorithms with samples

Citation preview

1

SHREE VENKATESHWARA

HI-TECH ENGINEERING COLLEGE

GOBI-638 455

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL

SUBJECT: DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY

SEMESTER / YEAR: V-SEM / III YEAR

2

Syllabus

1. Implementation of Sorting Algorithms2. Implementation of Binary Search Algorithm3. Implementation of Minimum Spanning Tree Algorithm4. Implementation of Knapsack Algorithm5. Implementation of All pair shortest Path Algorithm6. Implementation of Eight Queens Problem7. Implementation of Traveling Salesman Problem8. Implementation of Graph Coloring9. Implementation of Multistage Graphs

3

LIST OF EXPERIMENTS

SL.NO

DATENAME OF THE EXPERIMENT

MARKS

SIGNATURE

1.Apply the Divide and Conquer Technique to arrange a set of numbers using Merge Sort Method.

2.Search a an element from a given array using binary search method

3.Construct a Minimum Spanning Tree using Greedy Method

4. Solve the Knapsack Problem

5.

Perform Graph Traversals

a. Graph Traversals – Breadth First Searchb. Graph Traversals – Depth First Search pg:49

6. Implement the 8-Queens Problem using Backtracking

7. Implementation of Traveling Salesman Problem

8. Implementation of Multi stage graphs

9. Implementation of Graph Coloring

10. Implement Knapsack Problem using Backtracking

4

EX.NO:1 Apply the Divide and Conquer Technique to arrange a set of numbers usingDATE: Merge Sort Method

Aim:

To write a C program to perform merge sort using the divide and conquer technique.

Description:Divide and Conquer is a design technique for algorithms which divides a

problem into smaller instances, and the smaller instances are solved recursively. Then the solutions obtained for the smaller instances are combined to get a solution to the original problem.

Merge sort is successfully performed by the divide and conquer technique. It sorts a given array A[0..n-1] by dividing it into two halves A[0..[n/2]-1] and A[[n/2]..n-1], sorting each of them recursively and then merging the two smaller sorted arrays into a single sorted one.

Algorithm:Step 1: Start the process.Step 2: Declare the variables.Step3: Define the function called merge with appropriate parametersStep 4: Enter the list of elements to be sorted using the function StepStep 5: Divide the array list into two halves the lower array list and upper array list using the merge sort function call the mergesort function and computer the mid value = (low+high)/2.Step 6: again call the mergersort function with the arguments (low,mid) and (mid+1, high).Step 7: If low<high call the mergesort function by passing the arguments low, mid and high valuesStep 8: combine the two sorted arrays display the sorted elements using the function.Step 9: Stop the process.

//Mergesort Using Divide & Conquer#include<stdio.h>#include<conio.h>int a[10],b[10];int n,i,k,l,m;void mergesort(int,int);void merge(int,int,int);void main(){clrscr();printf("\t******************************************\n");printf("\t Mergesort Using Divides and Conquer\n");printf("\t******************************************\n");printf(" Enter The Input Size:");

5

scanf("%d",&n);printf(" Enter The Different Array Elements:");for(i=1;i<=n;i++)scanf("%d",&a[i]);mergesort(l,n);printf(" After Sorted Array Elements:\n");for(i=1;i<=n;i++)printf(" %d\n",a[i]);getch();}void mergesort(int low,int high){int mid;if(low<high){mid=(low+high)/2;mergesort(low,mid);mergesort(mid+1,high);merge(low,mid,high);}}void merge(int low,int mid,int high){l=low;m=mid+1;i=low;while((l<=mid)&&(m<=high)){if(a[l]<=a[m]){b[i]=a[l];l++;}else{b[i]=a[m];m++;}i++;}if(l>mid)for(k=m;k<=high;k++){b[i]=a[k];i++;}else{for(k=l;k<=mid;k++){b[i]=a[k];i++;}

6

}for(i=low;i<=high;i++)a[i]=b[i];}

/* OUTPUT */*****************************************Mergesort Using Divides and Conquer*****************************************

Enter The Input Size:5Enter The Different Array Elements: 23 56 1 78 34After Sorted Array Elements:123345678

RESULT:Thus the above program was executed and verified successfully.

7

EX.NO:2 Implementation of Binary SearchDATE :

Aim:To write a C program to perform merge sort using the divide and conquer

technique.

ALGORITHM:Step 1: Declare the array for the elements and other temporary variablesStep 2: Get the number of elements ‘n’ and get the elements.Step 3: Get the element to be searched e1 and initialize flag = f.Step 4: Assign low = 0, high = n-1.repeat the following until low value > high value

assign (low+high)/2 to midcheck whether e1<array of mid value, if so assign mid-1 to high.Otherwise check whether e1>array of mid value, if so assign mid+1 to low, Otherwise print the element found at position mid+1, assign flag= t.

Step 5: If flag = f, print element not found.Step 6: Exit from the program.

PROGRAM:

#include<stdio.h>#include<conio.h>void main(){int i,j,low,high,mid,n,a[20],e1,tmp;char flag='f';clrscr();printf("Binary Search\n");printf("enter number of elements\n");scanf("%d",&n);printf("enter the elements");for(i=0;i<n;i++)scanf("%d", &a[i]);printf("enter the element to be searched:");scanf("%d",&e1);for(i=0;i<n;i++){for(j=i+1;j<n;j++){if(a[i]>a[j]){tmp=a[i];a[i]=a[j];a[j]=tmp;}}}printf("sorted elements\n");

8

for(i=0;i<n;i++){printf("%d ",a[i]);}printf("\n");low=0;high=n-1;while(low<=high){mid=(low+high)/2;if(e1<a[mid])high=mid-1;else if(e1>a[mid])low=mid+1;else{printf("element %d found at position %d",e1,mid+1);flag='t';break;}}if(flag=='f'){printf("element %d not found",e1);}getch();}

OUTPUT:Binary Searchenter number of elements5enter the elements3485276014enter the element to be searched:27sorted elements14 27 34 60 85element 27 found at position 2

RESULT:Thus the above program was executed and verified successfully.

9

EX.NO:3 Construct a Minimum Spanning Tree using GreedyDATE: Method.

Aim:To write a C program to find the minimum spanning tree using greedy method

Description:A spanning tree of a connected graph is its connected acyclic sub graph, that contains all the vertices of the graph. A minimum spanning tree of a weighted connected graph is its spanning tree of the smallest weight, where the weight of a tree is defined as the sum of the weights on all its edges. The minimum spanning tree problem is the problem of finding a minimum spanning tree for a given weighted connected graph.The prim’s algorithm constructs a minimum spanning tree through a sequence of expanding sub trees. The initial sub tree in such a sequence consists of a single vertex selected arbitrarily from the set V of the graph’s vertices. On each iteration, we expand the current tree in the greedy manner by simply attaching to it the nearest vertex not in that tree. The algorithm stops after all the graph’s vertices have been included in the tree being constructed.

Algorithm:Step1: Start the program.Step2: ReadStep3: Using the get function get the number of vertices and enter their weights.Step4: Using the cal function calculate the minimum spanning tree.Step5: Display the minimum spanning tree for the given weighted graph.Step6: End the program.

Program://Minimum Spanning Tree Using Kruskal Algorithm#include<stdio.h>#include<conio.h>void main(){int v,i,j,d[10][10],r,k=1,count=1;int w[10],temp;char ch[10][2],ed[100][3],st[3];clrscr();printf("\t *********************************************\n");printf("\t Minimum Spanning Tree Using Kruskal Algorithm ");printf("\n\t ***********************************************\n");printf("\n Enter The No.Of Vertices :\t");scanf("%d",&v);printf("\n Enter The Name Of Vertices:\t");for(i=0;i<v;i++)scanf("%s",&ch[i]);printf("\n The Given Vertices is :\t");for(i=0;i<v;i++)printf("%s->",ch[i]);getch();printf("\n Enter The Edges and Weights:\n");for(i=0;i<v;i++){for(j=0;j<v;j++)

10

{scanf("\t %d",&d[i][j]);if((d[i][j]>0)&&(d[i][j]<=9)){strcpy(ed[k],ch[i]);strcat(ed[k],ch[j]);w[k]=d[i][j];k++;}}}k--;printf("\n Ordered Edges and Weights Are :\n");for(i=1;i<=k;i++)printf(" %s->%d\t",ed[i],w[i]);getch();for(i=0;i<k-1;i++){for(j=j+1;j<=k;j++){if(w[i]>w[j]){temp=w[i];strcpy(st,ed[i]);w[i]=w[j];strcpy(ed[i],ed[j]);w[i]=temp;strcpy(ed[j],st);}}}printf("\n Ordered Edges And Weight Are:\n");for(i=1;i<=k;i++)printf(" %s->%d\t",ed[i],w[i]);i=1;printf("\n The Minimum Spanning Tree\n");while(1){if(w[i]!=temp){count++;printf(" %s->%d ",ed[i],w[i]);}temp=w[i++];if(count==v)break;}getch();

}

11

/* OUTPUT */***************************************************Minimum Spanning Tree Using Kruskal Algorithm***************************************************

Enter The No.Of Vertices : 4Enter The Name Of Vertices : A B C DThe Given Vertices is : A->B->C->D->Enter The Edges and Weights:0 2 3 42 0 5 43 5 0 44 4 4 0Ordered Edges and Weights Are :

AB->2 AC->3 AD->4 BA->2 BC->5 BD->4 CA->3 CB->5 CD->4 DA->4 DB->4 DC->4

Ordered Edges And Weight Are:AB->2 AC->3 AD->4 BA->2 DC->5 BC->4 BD->3 CA->5 CB->4 CD->4 DA->4 DB->4

The Minimum Spanning TreeAB->2 AC->3 AD->4

RESULT:Thus the above program was executed and verified successfully.

12

EX.NO:4 Solve the Knapsack Problem using Greedy Method.DATE:

Aim:To write a C program to solve the knapsack problem using greedy method.

Description:The knapsack problem arises whenever there is resource allocation with financial

constraints. Given a fixed budget, how do you select what things you should buy. Everything has a cost and value, so we seek the most value for a given cost.   The term knapsack problem invokes the image of the backbacker who is constrained by a fixed-size knapsack and so must fill it only with the most useful items.

The typical formulation in practice is the 0/1 knapsack problem,   where each item must be put entirely in the knapsack or not included at all. Objects cannot be broken up arbitrarily, so its not fair taking one can of coke from a six-pack or opening the can to take just a sip. It is this 0/1 property that makes the knapsack problem hard, for a simple greedy algorithm finds the optimal selection whenever we are allowed to subdivide objects arbitrarily.   For each item, we could compute its ``price per pound'', and take as much of the most expensive item until we have it all or the knapsack is full. Repeat with the next most expensive item, until the knapsack is full. Unfortunately, this 0/1 constraint is usually inherent in most applications.

Issues that arise in selecting the best algorithm include: Does every item have the same cost/value or the same size? - If each item is worth the same

amount to us as any other item, say $1, I maximize my value by taking the greatest number of items. In this case the optimal solution is to sort the items in order of increasing size and insert them into the knapsack in this order until nothing fits.   The problem is solved similarly when each object has the same size but the costs are different. These are the easy cases of knapsack.

Does each item have the same ``price per pound''? - In this case, our problem is equivalent to ignoring the price and just trying to minimize the amount of empty space left in the knapsack.   Unfortunately, even this restricted version of the problem is NP-complete, and so we cannot expect an efficient algorithm that always solves the problem. Don't lose hope, however, because knapsack proves to be an “easy” hard problem, one that can usually be handled with the algorithms described below.

Algorithm:Step1: Start the program.Step2: Get the knapsack size value and weight.Step3: Sort the profit and weight in descending order.Step4: Read the n no. of profits and weight values, m,n values, number of items, capacity of the bag, weight of the item and value of the items.Step5: Calculate the p[i]/w[i] >= p[i+1] / w[i+1] values.Step6: Use the ratio of accumulated profit to capacity.Step7: Find the optimal solution for the items using the algorithm.Step8: Stop the process.

//Knapsack Problem Using Greedy Method#include<stdio.h>#include<conio.h>void main(){int n,m,tp,tpw,tw,i,j;

13

float v[10],w[10],s[10],t;float pw[10],x[10];clrscr();printf("\n\t ****************************************");printf("\n\t Knapsack Problem Using Greedy Method");printf("\n\t ****************************************");printf("\n Enter Item:\t");scanf("%d",&n);printf("\n Enter The Capacity Of Knapsack:\t");scanf("%d",&m);for(i=1;i<=n;i++){printf("\n Enter The Profit And Weight:\t");scanf("%f%f",&w[i],&v[i]);pw[i]=v[i]/w[i];}printf("\n\n Probability and Weight Before Sorting:");for(i=1;i<=n;i++){printf("\n\n%f\t%f\t%f",pw[i],w[i],v[i]);}getch();for(i=1;i<=n;i++){for(j=i+1;j<=n;j++){if(pw[i]<pw[j]){tpw=pw[i];pw[i]=pw[j];pw[j]=tpw;tp=v[i];v[i]=v[j];v[j]=tp;tw=w[i];w[i]=w[j];w[j]=tw;}}}printf("\n\n Probability And Weight After Sorting:");for(i=1;i<=n;i++){printf("\n\n%f\t%f\t%f",pw[i],w[i],v[i]);}getch();for(i=1;i<=n;i++){x[i]=0.0;}for(i=1;i<=n;i++)

14

{if(v[i]>m)break;x[i]=1.0;m=m-v[i];}if(i<=n){x[i]=m/v[i];}printf("\n\n The Result Is:");for(i=1;i<=n;i++){printf("\n\n %f",x[i]);}printf("\n\n Solution Is:");for(i=1;i<=n;i++){printf("\n\n %f*%f=%f",v[i],x[i],v[i]*x[i]);t+=v[i]*x[i];}printf("\n\n Total Is %f",t);getch();}

/* OUTPUT */****************************************Knapsack Problem Using Greedy Method****************************************

Enter Item: 3Enter The Capacity Of Knapsack : 50Enter The Profit And Weight : 2 35Enter The Profit And Weight : 4 70Enter The Profit And Weight : 3 60

Probability and Weight Before Sorting:17.500000 2.000000 35.00000017.500000 4.000000 70.00000020.000000 3.000000 60.000000

Probability And Weight After Sorting:20.000000 3.000000 60.00000017.500000 4.000000 70.00000017.000000 2.000000 35.000000

The Result Is:0.8333330.0000000.000000

Solution Is:

15

60.000000*0.833333=49.99999970.000000*0.000000=0.00000035.000000*0.000000=0.000000

Total Is 50.000000

RESULT:Thus the above program was executed and verified successfully.

16

EX.NO:5 Implementation Of All Pair Shortest Path AlgorithmDATE :

5.a. Graph Traversals – Breadth First Search

Aim:To write a C program to perform the graph traversal using BreadtFirst Search.

Description:Breadth first search proceeds in a concentric manner by visiting first all the vertices that are adjacent to a starting vertex, then all the unvisited vertices two edges apart from it, and so on, until all the vertices in the same connected component as the starting vertex are visited. If there still remain unvisited vertices, the algorithm has to be restarted at an arbitrary vertex of another connected component of the graph.It is convenient to use a queue to trace the operation of breadth first search. The queue is initialized with the traversal’s starting vertex, which is marked as visited. On each traversal the algorithm identifies all unvisited vertices that are adjacent to the front vertex, marks them as visited, and adds them to the queue; after that the front vertex is removed from the queue.BFS traversal can be done by constructing a breadth first search forest. The traversal’s starting vertex serves as the root of the first tree in such a forest. Whenever a new unvisited vertex is reached for the first time, the vertex is attached as a child to the vertex it is being reached from with an edge called a tree edge. If an edge leading to a previously visited vertex other than its immediate predecessor is encountered the edge is noted as a cross edge.

Algorithm:Step1: Start the process.Step2: Input the no. of vertices and edges for the graph to be searched.Step3: Graph G with its vertices marked with consecutive integers in the order they have been first encountered by the BFS traversal.Step4: Mark each vertex in V with 0 as a mark of being “unvisited”.Step5: The function visits recursively all the unvisited vertices connected to vertex vStep6: Assign the vertices numbers in the order they are encountered.Step7: Initialize the queue with the vertices.Step7: Stop the process.

5.b. Graph Traversals – Depth First SearchAim:

To write a C program to perform graph traversal by Depth First Search Method.

Description:Depth first search starts visiting vertices of a graph at an arbitrary vertex by marking it as having been visited. On each iteration, the algorithm proceeds to an unvisited vertex that is adjacent to the one it is currently in. This process continues until a dead end – vertex with no adjacent unvisited vertices is encountered. At a dead end, the algorithm backs up one edge to the vertex it came from and tries to continue, visiting unvisited vertices from there. It is convenient to use a stack to trace the operation of the depth first search.

17

The algorithm eventually halts after backing up to the starting vertex, with the latter being a dead end. By then, all the vertices in the same connected component as the starting vertex have been visited. If unvisited vertices still remain, the depth first search must be restarted at any one of them.BFS starts by constructing a depth first search forest. The traversal’s starting vertex serves as the root of the first tree in a forest. When ever a new unvisited vertex is reached for the first time, it is attached as a child to the vertex from which it is being reached. Such an edge is called a tree edge because the set of all such edges forms a forest. The algorithm may also encounter an edge leading to a previously visited vertex other than its immediate predecessor. Such an edge is a back edge because it connects a vertex to its ancestor, other than the parent, in the depth first search forest.

Algorithm:Step1: Start the process.Step2: Input the no. of vertices and edges for the graph to be searched.Step3: Graph G with its vertices marked with consecutive integers in the order they have been first encountered by the DFS traversal.Step4: Mark each vertex in V with 0 as a mark of being “unvisited”.Step5: The function visits recursively all the unvisited vertices connected to vertex vStep6: Assign the vertices numbers in the order they are encountered.Step7: Stop the process.

PROGRAM://GRAPH TRAVERSALS (DFS & BFS)#include<stdio.h>#include<conio.h>int n,m[10][10],i,j,visit[10],s,q[10],f,r;void breadth(int);void breadth1(int);void dfs(int);void main(){int ch, ch1;clrscr();printf("\n\t *********************\n");printf("\n\t Graph ravesal \n");printf("\n\t ********************\n");printf("\n Enter the No. of Vertices :");scanf("%d",&n);printf("\n Enter the adjacency matrix:");for(i=0;i<n;i++){for(j=0;j<n;j++){scanf("%d",&m[i][j]);}}while(1){printf("\n\t 1-> BFS \n\t 2-> DFS \n\t 3-> QUIT\n");printf("\n\n Enter your choice:");

18

scanf("%d",&ch);switch(ch){case 1:f=0, r=0;printf("\n Enter the starting vertices:");scanf("%d",&s);printf("\n\t\t BREADTH FIRST SEARCH \n");for(i=0;i<n;i++)visit[i]=0;breadth(s);getch();break;case 2:printf("\n Enter the starting verticies:");scanf("%d",&s);printf("\n\t\t\t DEPTH FIRST SEARCH:\n\n:");for(i=0;i<n;i++)visit[i]=0;for(i=s;i<n;i++)dfs(i);getch();break;default:exit(0);break;}} }void breadth(int k){if(visit[k]!=1){visit[k]=1;printf("\n\t\t\t %2c",65+k);}breadth1(k);}void breadth1(int k){for(i=0;i<n;i++)if((visit[i]!=1)&&(m[k][i]!=0)){q[++r]=1;visit[i]=1;printf("\t%2c",65+i);}while(f<r+1){f++;breadth(q[f]);

19

}}void dfs(int k){if(visit[k]!=1){visit[k]=1;printf("\t%2c",65+k);}for(j=0;j<n;j++){if((visit[j]!=1)&&(m[k][j]!=0))dfs(j);}}

/* OUTPUT */*********************Graph Traversals********************

Enter the No. of Vertices :4Enter the adjacency matrix:0 1 1 00 0 0 10 0 0 10 0 0 0

1-> BFS2-> DFS3-> QUIT

Enter your choice:1Enter the starting vertices:0

BREADTH FIRST SEARCHA B C D1-> BFS2-> DFS3-> QUIT

Enter your choice:2Enter the starting verticies:0

DEPTH FIRST SEARCH:A B D C

1-> BFS2-> DFS3-> QUIT

Enter your choice:3

RESULT:Thus the above program was executed and verified successfully.

20

EX.NO:6 Implement the 8-Queens Problem using Backtracking.DATE:

Aim:To write a C program to find the solution to the N queens problem using the backtracking

method.Description:

The problem is to find all ways of placing n non-taking queens on a n by n board. A queen attacks all cells in its same row, column, and either diagonal. Therefore, the objective is to place n queens on an n by n board in such a way that no two queens are on the same row, column or diagonal. Below we show a solution on a standard 8 by 8 chessboard.

The number of solutions for n = 1,2,...,15, is 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, 2279184.

A solution to the queens problem may be viewed as a permutation. For each column we record the number of the row in which the queen appears. Every column contains exactly one queen and every row contains exactly one queen; this is the condition for non-taking rooks used in the permutation.

Algorithm:Step1: Start the process.Step2: Enter the no. of queens.Step3: Using the queen function place all the queens.Step4: Check the position to place the queen is free or not.Step5: Check finally if all the queens are placed.Step6: Check for all the constraints, check the rows and columnsStep7: If no clash then all the queens are placed in correct position.

Program://N Queen Problem#include<stdio.h>#include<conio.h>#include<math.h>struct queen{int x[11];

21

}q;void nqueen(int,int);int place(int,int);void write(int);void nqueen(int k, int n){int i,n1;for(i=1;i<=n;i++){if(place(k,i)){q.x[k]=i;if(k==n){clrscr();write(n1);}elsenqueen(k+1,n);}}}int place(int k, int i){int j;for(j=1;j<=k;j++){if((q.x[j]==i)||(abs(q.x[j]-i)==abs(j-k)))return 0;}return 1;}void write(int n1){int i,m;printf("\n\n\n\t\t\t N-Queen Problem \n\n\n\n");for(i=1;i<=n1+1;i++){printf("\t\t\t");for(m=1;m<=n1+1;m++){if (m==q.x[i])printf(" Q ");elseprintf(" _ ");}printf("\n\n");}}void main(){

22

int n;clrscr();printf("\n\t\t ***********************\n");printf("\n\t\t NQueen Problem \n");printf("\n\t\t ***********************\n");printf("\n\n Enter the value of n: ");scanf("%d",&n);nqueen(1,n);getch();}

/ * OUTPUT */***********************NQueen Problem***********************Enter the value of n: 8

N-Queen Problem_ _ _ _ _ _ _ Q_ _ _ Q _ _ _ _Q _ _ _ _ _ _ __ _ Q _ _ _ _ __ _ _ _ _ Q _ __ Q _ _ _ _ _ __ _ _ _ _ _ Q __ _ _ _ Q _ _ _

RESULT:Thus the above program was executed and verified successfully.

23

EX.NO:7 Find the solution of Traveling Salesperson ProblemDATE: using Branch and Bound Technique.

Aim:To write a C program to solve the traveling salesman problem using the branch and bound

method.

Description:The traveling salesman problem can be solved using the branch and bound method, if a reasonable lower bound on tour lengths. One very simple lower bound can be obtained by finding the smallest element in the intercity distance matrix D and multiplying it by the number of cities n. We can compute a lower bound on the length l of any tour as follows:For each city I, 1≤i≤n, find the sum si of the distances from city i to the two nearest cities. Compute the sum s of these n numbers; divide the result by 2; and if all the distances are integers round up the result to the nearest integer: lb= [s/2]BB TRAVEL(cost[ ],n)u = city 1Repeat while(all cities visited)Find all cities w adjacent from uIf (cost of edge is minimum) and (city not yet visited)Move to that city and mark it visitedu = current cityEnd ifEnd RepeatCalculate path costPrint shortest path and its costEnd TRAVEL

Algorithm:Step1: Start the program.Step2: Start traversing from the initial node u=city1.Step3: Repeat the following steps until all the cities are visited exactly once.Step4: Calculate the path cost for each route.Step5: Print the shortest path and its cost.Step6: Stop the Program.

PROGRAM:#include<stdio.h>#include<conio.h>void main(){int w[5][5]={{99,3,1,5,8},{3,99,6,7,9},{1,6,99,4,2},{5,7,4,99,3},{8,9,2,3,99} };int mina,minb,minc,mind,mine;int s,lb,i;clrscr();mina=w[0][1]+w[0][2];minb=w[1][0]+w[1][2];minc=w[2][0]+w[2][4];

24

mind=w[3][2]+w[3][4];mine=w[4][2]+w[4][3];s=mina+minb+minc+mind+mine;printf("\n\t\t *****************************");printf("\n\t\t TRAVELING SALESMAN");printf("\n\t\t *****************************\n");for(i=0;i<=11;i++){if(i==0){s=mina+minb+minc+mind+mine;lb=s/2;printf("\t Rootnode value=\t%d\n",lb);}else if(i==1){s=mina+minb+minc+mind+mine;lb=s/2;printf("\t(a,b)value=\t%d\n",lb);i++;}else if(i==2){printf("\t(a,c)value=\t%d\n",lb);}else if(i==3){mina=w[0][3]+w[0][2];mind=w[3][0]+w[3][4];s=mina+minb+minc+mind+mine;lb=s/2;printf("\t(a,d)value=\t%d\n",lb);}else if(i==4){mina=w[0][4]+w[0][2];mind=w[3][0]+w[3][4];mine=w[4][0]+w[4][2];s=mina+minb+minc+mind+mine;lb=s/2;printf("\t(a,e)value=\t%d\n",lb);}else if(i==5){mina=w[0][1];minb=w[1][2]+w[1][0];minc=w[2][1]+w[2][0];mind=w[3][2]+w[3][4];mine=w[4][2]+w[4][3];s=mina+minb+minc+mind+mine;lb=s/2;

25

printf("\t(a,b,c)value=\t%d\n",lb);}else if(i==6){minb=w[1][3]+w[1][0];minc=w[2][0]+w[2][4];mind=w[3][1]+w[3][4];mine=w[4][2]+w[4][3];s=mina+minb+minc+mind+mine;lb=s/2;printf("\t(a,b,d)value=\t%d\n",lb);}else if(i==7){minb=w[1][4]+w[1][0];minc=w[2][0]+w[2][4];mind=w[3][2]+w[3][4];mine=w[4][1]+w[4][2];s=mina+minb+minc+mind+mine;lb=s/2;printf("\t(a,b,e)value=\t%d\n",lb);}else if(i==8){mina=w[0][1];minb=w[1][2];minc=w[2][3];mind=w[3][4];mine=w[4][0];lb=mina+minb+minc+mind+mine;printf("\n\t First tour\n");printf("\t(a,b,c,d(e,a))value=\t%d\n",lb);}else if(i==9){minc=w[2][4];mine=w[4][3];mind=w[3][0];lb=mina+minb+minc+mind+mine;printf("\n\t Better tour\n");printf("\t(a,b,c,e(d,a))value=%d\n",lb);}else if(i==10){minb=w[1][3];mind=w[3][2];minc=w[2][4];mine=w[4][0];lb=mina+minb+minc+mind+mine;printf("\n\t Inferior tour\n");printf("\t(a,b,d,c(e,a))value=%d\n",lb);

26

}else if(i==11){minc=w[2][0];mind=w[3][4];mine=w[4][2];lb=mina+minb+minc+mind+mine;printf("\n\t Optimal tour\n");printf("\t(a,b,d,e(c,d))value=%d\n",lb);}}printf("\n");getch();}

/* OUTPUT */*****************************TRAVELING SALESMAN*****************************Rootnode value = 14(a,b)value = 14(a,d)value = 15(a,e)value = 19(a,b,c)value = 15(a,b,d)value = 15(a,b,e)value = 18First tour(a,b,c,d(e,a))value = 24Better tour(a,b,c,e(d,a))value = 19Inferior tour(a,b,d,c(e,a))value = 24Optimal tour(a,b,d,e(c,d))value = 16

RESULT:Thus the above program was executed and verified successfully.

27

EX.NO:8 Implementation of Multi stage graphsDATE :

Aim:To write a C program to perform multi stage graphs

Description:

(Space to write program)Program:

(Space to write program)

28

(Space to write program)

29

(Space to write program)

RESULT:Thus the above program was executed and verified successfully.

30

EX.NO:9 Implementation of graph coloringDATE :

Aim:To write a C program to perform graph coloring

Description:

(Space to write program)

Program:

(Space to write program)

(Space to write program)

(Space to write program)

RESULT:Thus the above program was executed and verified successfully.

31

EX.NO:10 Implement Knapsack Problem using BacktrackingDATE:

Aim:To write a C program to solve the knapsack problem using the backtracking technique.

Description:The 0-1 KnapsackThe knapsack problem arises whenever there is resource allocation with financial constraints. Given a fixed budget, how do you select what things you should buy. Everything has a cost and value, so we seek the most value for a given cost. The term knapsack problem invokes the image of the backbacker who is constrained by a fixed-size knapsack and so must fill it only with the most useful items.The typical formulation in practice is the 0/1 knapsack problem, where each item must be put entirely in the knapsack or not included at all. Objects cannot be broken up arbitrarily, so its not fair taking one can of coke from a six-pack or opening the can to take just a sip. It is this 0/1 property that makes the knapsack problem hard, for a simple greedy algorithm finds the optimal selection whenever we are allowed to subdivide objects arbitrarily. For each item, we could compute its price per pound'', and take as much of the most expensive item until we have it all or the knapsack is full. Repeat with the next most expensive item, until the knapsack is full. Unfortunately, this 0/1 constraint is usually inherent in most applications.Consider of size K and we want to select from a set of n objects , where the ith object has size si and value vi, a subset of these objects to maximize the value contained in the knapsack with the contents of the knapsack less than or equal to K.Suppose that K = 16 and n = 4, and we have the following set of objects ordered by their value density.i v i s i v i/ s i

1 $45 3 $152 $30 5 $ 63 $45 9 $ 54 $10 5 $ 2Construct the state space where each node contains the total current value in the knapsack, the total current size of the contents of the knapsack, and maximum potential value that the knapsack can hold. In the algorithm, we will also keep a record of the maximum value of any node (partially or completely filled knapsack) found so far. When we perform the depth-first traversal of the state-space tree, a node is "promising" if its maximum potential value is greater than this current best value.Begin the state space tree with the root consisting of the empty knapsack. The current weight and value are obviously 0. To find the maximum potential value we treat the problem as if it were the fractional knapsack problem and we were using the greedy algorithmic solution to that problem. We have shown that the greedy approach to the fractional knapsack problem yields an optimal solution. We place each of the remaining objects, in turn, into the knapsack until the next selected object is too big to fit into the knapsack. We then use the fractional amount of that object that could be placed in the knapsack to determine the maximum potential value.totalSize = currentSize + size of remaining objects that can be fully placedbound (maximum potential value) = currentValue + value of remaining objects fully placed +(K - totalSize) * (value density of item that is partially placed)For the root node, currentSize = 0, currentValue = 0totalSize = 0 + s1 + s2 = 0 + 3 + 5 = 8bound = 0 + v1 + v2 + (K - totalSize) * (v3/s3) = 0 + $45 + $30 + (16 - 8) * ($5) = $75 + $40 = $115

32

From the root, we add two children at level 1 -- the node where the first item is included in the knapsack and the node where it is not. For the child where the first item is not included in the knapsack, the calculation for the bound proceeds as follows:totalSize = 0 + s2 + s3 = 5 + 9 = 14bound = 0 + v2 + v3 + (K - totalSize) * (v4/s4) = 0 + $30 + $45 + (16 - 14) * ($2) = $79The state spaced traversed by the backtracking algorithm is displayed below. When the bound of a node is less than or equal to the current maximum value, or adding the current item to the node causes the size of the contents to exceed the capacity of the knapsack, the subtrees rooted at that node are pruned, and the traversal backtracks to the previous parent in the state space tree.

For n objects, there are 2n possible solution sets -- the ith object is either in or out of the solution set. The state space, therefore, is represented as a complete binary tree with 2n leaves. Such a tree will have a total of 2n+1 - 1 nodes. The backtracking algorithm, therefore, has a worst-case bound that is O(2n). With pruning the actual number of nodes "visited" by the algorithm is much less.

Algorithm:

Step1: Start the program.Step2: Get the knapsack size, value and weight.Step3: Get the weight and profit in descending order.Step4: Use the profit and weight and also the perform knap functionStep5: Using the bound function and check the condition to display the value.Step6: Display the solution for the knapsack problem.

33

Program://Knapsack Problem Using Backtracking#include<stdio.h>#include<conio.h>int w[25],m,j,n,x[25],p[25],y[25],fp,fw;void bknap(int,int,int);int bound(int,int,int);void main(){int i;clrscr();printf("\n\t\t **************************************");printf("\n\t\t Knapsack Problem Using Backtracking");printf("\n\t\t***************************************");printf("\n\t\t Enter the Knapsack Capacity :\t");scanf("%d",&m);printf("\n\t\t Enter the number of items :\t");scanf("%d",&n);printf("\n\t\t Enter the weight and its profit \t");for(i=1;i<=n;i++){x[i]=0;printf("\n\t\t Enter the weight :\t");scanf("%d",&w[i]);printf("\n\t\t Enter the profit :\t");scanf("%d",&p[i]);}bknap(1,0,0);printf("\n\t\t The Result is :\t");for(i=1;i<=n;i++)printf("%d",y[i]);getch();}void bknap(int k, int cp, int cw){if((cw+w[k])<=m){y[k]=1;if(k<n)bknap(k+1,cp+p[k],cw+w[k]);if((cp+p[k]>fp)&&(k==n)){fp=cp+p[k];fw=cw+w[k];for(j=1;j<=k;j++)x[j]=y[j];}}if((bound(cp,cw,k))>=fp){y[k]=0;

34

if(k<n)bknap(k+1,cp,cw);if((cp>fp)&&(k==n)){fp=cp;fw=cw;for(j=1;j<=k;j++)x[j]=y[j];}}}int bound(int cp, int cw, int k){int i,b,c;b=cp;c=cw;for(i=k+1;i<=n;i++){c=c+w[i];if(c<=m)b=b+p[i];elsereturn (b+(1-(c-m/w[i])*p[i]));}return b;}

/* OUTPUT */**************************************Knapsack Problem Using Backtracking***************************************Enter the Knapsack Capacity : 20Enter the number of items : 3Enter the weight and its profitEnter the weight : 18Enter the profit : 25Enter the weight : 15Enter the profit : 24Enter the weight : 10Enter the profit : 15The Result is : (1,0,0)

RESULT:Thus the above program was executed and verified successfully.