Vous êtes sur la page 1sur 43

KNAPSACK PROBLEM BY GREEDY METHOD

PROBLEM STATEMENT:
The knapsack problem in combinatorial optimization states:
Given a set of items, each with a weight and a value, determine
the number of each item to include in a collection so that the
total weight is less than or equal to a given limit and the total
value is as large as possible.
ALGORITHM:
Algo_Greedy_Knapsack (m,n)
{

/*p[1:n] and w[1:m] contains profits and weights


respectively of the n objects ordered such that
p[i]/w[i]>=p[i+1]/w[i+1] where m is the knapsack size and
x[1:n] is the solution vector.*/
for i=1 to n do x[i]=0.0; //initializes the solution vector
u=m; /*u keeps track of how much portion of the
knapsack is left*/
for i=1 to n do
{
if (w[i]>u) then break;
x[i]=1.0;
u=u-w[i];
}
if (i<=n) then x[i]=u/w[i];

C PROGRAM:
# include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0; int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++) {
if (weight[i] > u)
break;
else {
x[i] = 1.0; tp = tp+profit[i];
u = u - weight[i];
}
} if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}
int main() {
float weight[20], profit[20], capacity;
int num, i, j; float
ratio[20], temp;
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);

printf("\nEnter the wts and profits of each object:-\n");


for (i = 0; i < num; i++) { scanf("%f %f", &weight[i],
&profit[i]);
}
printf("\nEnter the capacityacity of knapsack:- ");
scanf("%f", &capacity); for (i = 0; i < num; i++) {
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return(0);
}

PRIMS ALGORITHM BY GREEDY METHOD


PROBLEM STATEMENT:
Prim's algorithm is a greedy algorithm that finds a minimum
spanning tree for a weighted undirected graph. This means it
finds a subset of the edges that forms a tree that includes every
vertex, where the total weight of all the edges in the tree is
minimized. The algorithm operates by building this tree one
vertex at a time, from an arbitrary starting vertex, at each step
adding the cheapest possible connection from the tree to
another vertex.
ALGORITHM:
Algo_Greedy_Prim (E,cost,V,t)
{
Let (k,l) be an edge of min.cost in E;
min.cost=cost[k,l]; t[1,1]=k; t[1,2]=l;
for i=1 to V do
{
if (cost[i,l]<cost[i,k])
then near[r]=l;
else

near[i]=k;
}

near[k]=near[l]=0;
for i=2 to v-1 do
{
Let j be an index such that near[j]!=0 and
cost[j,near[j]] is minimum; t[i,1]=j;
t[1,2]=near[j];
min.cost=min.cost+cost[j,near[j]];
near[j]=0; for k=1 to v do
if (near[k]!=0 and cost[k,near[k]]>cost[k,j])
then near[k]=j;
}
return min.cost;
}
C PROGRAM:
#include<stdio.h>
#include<conio.h>
int n, cost[10][10];
void prim() {
int i, j, startVertex, endVertex;
int k, nr[10], temp, minimumCost = 0, tree[10][3];
int temp = cost[0][0];
for (i = 0; i < n; i++)
{

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


{
if (temp > cost[i][j])
{
temp = cost[i][j];
startVertex = i;
endVertex = j;
}
}
}
tree[0][0] = startVertex;
tree[0][1] = endVertex;
tree[0][2] = temp;
minimumCost = temp;
for (i = 0; i < n; i++) {
if (cost[i][startVertex] < cost[i][endVertex])
nr[i] = startVertex;
else
nr[i] = endVertex;
}
nr[startVertex] = 100;
nr[endVertex] = 100;
temp = 99;
for (i = 1; i < n - 1; i++)
{
for (j = 0; j < n; j++)
{
if (nr[j] != 100 && cost[j][nr[j]] < temp)
{
temp = cost[j][nr[j]];

k = j;
}
}
tree[i][0] = k;
tree[i][1] = nr[k]; tree[i][2] = cost[k][nr[k]];
minimumCost = minimumCost + cost[k][nr[k]];
nr[k] = 100;
for (j = 0; j < n; j++)
{
if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])
nr[j] = k;
}
temp = 99;
}
printf("\nThe min spanning tree is:\n");
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < 3; j++)
printf("%d\t", tree[i][j]);
printf("\n");
}
printf("\nMin cost : %d", minimumCost);
}
void main() {
int i, j;
clrscr();
printf("Enter the no. of vertices :");
scanf("%d", &n);
printf("\nEnter the costs of edges in matrix form :\n");
for (i = 0; i < n; i++)

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


{
scanf("%d", &cost[i][j]);
}
printf("\nThe matrix is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t", cost[i][j]);
}
printf("\n");
}
prim(); getch();
}

KRUSKALS ALGORITHM BY GREEDY METHOD


PROBLEM STATEMENT:
Kruskal's algorithm is a minimum-spanning-tree algorithm which
finds an edge of the least possible weight that connects any two
trees in the forest. It is a greedy algorithm in graph theory as it
finds a minimum spanning tree for a connected weighted graph
adding increasing cost arcs at each step. This means it finds a
subset of the edges that forms a tree that includes every vertex,
where the total weight of all the edges in the tree is minimized.
ALGORITHM:
Algo_Greedy_Kruskal (edgelist,E,V,t)
{
Sort the edges in ascending order of their costs by quick
sort;
for i=1 to V do parent[i]=-1;

//each vertex in diff. set

p=1;
min.cost=0.0;
for i=1 to E do
{
j=Find(edgelist[i].vertex1);
k=Find(edgelist[i].vertex2);
if(j!=k)

//if edge does not create a cycle

{
t[p][1]=edgelist[i].vertex1;
t[p][2]=edgelist[i].vertex2;
p=p+1;
min.cost=mincost+edgelist[i].cost;
union(j,k);
}
}
if (p!=(v-1)) then print: No spanning tree; else
return min.cost;
}
C PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> int
i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int); int uni(int,int);
void main()
{
clrscr();
printf("\nEnter the no. of vertices: ");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:\n");

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of Minimum Cost Spanning Tree are:\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}

cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost = %d\n",mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

N QUEENS PROBLEM BY BACKTRACKING


ALGORITHM
PROBLEM STATEMENT:
The n queens puzzle is the problem of placing n number of chess
queens on an nn chessboard so that no two queens threaten
each other. Thus, a solution requires that no two queens share
the same row, column, or diagonal for all natural numbers n
with the exception of n=2 and n=3.
ALGORITHM:
Algo_N_Queens (k,n)
{
for i=1 to n do
{
if (Place(k,i)=TRUE) then
{
x[k]=i;
if(k=n) then write (x[1:n]);
else N_Queens (k+1,n);
}
}
}

Algo_Place (k,i)
{
for j=1 to k-1 do
if((x[j]=i) or (Abs(x[j]-i)=Abs(j-i))) then return FALSE;
return TRUE;
}
C PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h> int
chess_board[20], count; int
display(int); void
queen_function(int, int); int
placeholder(int, int);
void queen_function(int row_value, int limit)
{
int column_value;
for(column_value = 1; column_value <= limit;
column_value++)
{
if(placeholder(row_value, column_value))
{
chess_board[row_value] = column_value;
if(row_value == limit)
{
display(limit);
}
else
{

queen_function(row_value + 1, limit);
}
}
}
}
int placeholder(int row_value, int column_value)
{
int count;
for(count = 1; count <= row_value - 1; count++)
{
if(chess_board[count] == column_value)
{
return 0;
}
else
{
if(abs(chess_board[count] - column_value) ==
abs(count - row_value))
{
return 0;
}
}
}
return 1;
}
int display(int limit)
{
int m, n;
printf("\n\n\tPossible Solution %d:\n\n", ++count);
for(m = 1; m <= limit; m++)
{
printf("\t[%d]", m);
}
for(m = 1; m <= limit; m++)

{
printf("\n\n[%d]", m);
for(n = 1; n <= limit; n++)
{
if(chess_board[m] == n)
{
printf("\tQ");
}
else
{
printf("\t*");
}
}
}
}
void main()
{
int limit;
printf("\nEnter Number of Queens:\t");
scanf("%d", &limit);
if(limit <= 3)
{
printf("\nNumber should be greater than 3 to form a
Matrix\n");
}
else
{
queen_function(1, limit);
}
printf("\n\n");
}

FLOYD-WARSHALL ALGORITHM BY DYNAMIC


PROGRAMMING
PROBLEM STATEMENT:
The Floyd-Warshall algorithm is an algorithm for finding shortest
paths in a weighted graph with positive or negative edge weights
(but with no negative cycles). A single execution of the algorithm
will find the lengths (summed weights) of the shortest paths
between all pairs of vertices, though it does not return details of
the paths themselves.
ALGORITHM:
Algo_Floyd_Warshall (cost,A,n)
{
/*cost[1:n,1:n] is the cost adjacency matrix of a graph with
n vertices; A[i][j] is the cost of a shortest path from vertex i
to vertex j; cost[i][j]=0 for 1<=i<=n;*/
for i=1 to n do
{
for j=1 to n do
{
A[i][j]=cost[i][j];
}

//copy cost to matrix A

}
for k=1 to n do
{
for i=1 to n do
{
A[i][j]=min(A[i][j], A[i][k]+ A[k][j]);
}
}}

C PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
void floyd(int);
int w[MAX][MAX], d[MAX][MAX][MAX];
void main()
{
int i, j,k,v;
clrscr();
printf("Enter the no. of vertices in the graph: \n");
scanf("%d",&v);
printf("Enter the weight matrix: \n");
for(i=1;i<=v;i++)
{
for(j=1;j<=v;j++)
scanf("%d",&w[i][j]);
}
floyd(v);
getch();
}
void floyd(int v)
{
int k, i,j;
k=0; for(i=1;i<=v;i++)
{
for(j=1;j<=v;j++)
d[k][i][j]=w[i][j];
}
for(k=1;k<=v;k++)

{
for(i=1;i<=v;i++)
{
for(j=1;j<=v;j++)
d[k][i][j]=min(d[k-1][i][j], d[k-1][i][k]+ d[k1][k][j]);
}
}
for(k=0;k<=v;k++){
printf(" k=%d \n",k);
for(i=1;i<=v;i++)
{
printf("\n");
for(j=1;j<=v;j++)
printf("\t %d",d[k][i][j]);
}
printf("\n \n ");
}
}

MATRIX CHAIN MULTIPLICATION BY


DYNAMIC PROGRAMMING
PROBLEM STATEMENT:
Matrix chain multiplication (or Matrix Chain Ordering Problem,
MCOP) is an optimization problem that can be solved using dynamic
programming. Given a sequence of matrices, the goal is to find the
most efficient way to multiply these matrices. The problem is not
actually to perform the multiplications, but merely to decide the
sequence of the matrix multiplications involved. For example, for four
matrices A, B, C, and D, we would have: ((AB)C)D = ((A(BC))D) =
(AB)(CD) = A((BC)D) = A(B(CD)) ALGORITHM:
Algo_Matrix_Chain_Order (p)
{
n=length(k)-1;
for i=1 to n do m[i][j]=0;
for l=2 to n do
{
for i=1 to n-l+1 do
{
j=i+l-1;
m[i][j]=;
for k=1 to j-1 do
{
q = m[i][k] + m[k+1][j] + pi-1 x pk x pj;
if(q<m[i][j])
{

m[i][j]=q;
s[i][j]=k;
}
}
}
}
}
C PROGRAM:
#include<stdio.h>
int chain(int index[20][20],int chain_matrix[],int i,int j);
void print_order(int index[20][20],int i,int j);
int main()
{
int size,i,value; int
chain_matrix[100];
int index[20][20];
printf("Enter the number of matrices: ");
scanf("%d",&size);
printf("\nEnter the dimensions of %d matrices:\n",size);
printf("\n");
for(i=0;i<size+1;i++)
{
printf("Enter the dimensions of the matrix: ");
scanf("%d",&chain_matrix[i]);
}
value=chain(index,chain_matrix,1,size);
printf("\nNumber of multiplication: %d\n\n",value);
printf("\nThe Optimal order is: ");
print_order(index,1,size);
getch();
return 0;

}
int chain(int index[20][20],int chain_matrix[],int i,int j)
{
if(i==j) return 0;
int k,count; int min=1000000;
for (k=i;k<j;k++)
{
count=chain(index,chain_matrix,i,k)+chain(index,
chain_matrix,k+1,j)+chain_matrix[i1]*chain_matrix[k]*
chain_matrix[j];
if(count<min)
{
min=count;
index[i][j]=k;
}
}
return min;
}
void print_order(int index[20][20],int i,int j)
{
if(i==j)
printf("M%d",i);
else
{
printf("(");
print_order(index,i,index[i][j]);
print_order(index,index[i][j]+1,j);
printf(")");
}
}

BINARY SEARCH BY RECURSION


PROBLEM STATEMENT:
Binary search is a search algorithm that finds the position of a
target value within a sorted array. It compares the target value
to the middle element of the array; if they are unequal, the half
in which the target cannot lie is eliminated and the search
continues on the remaining half until it is successful.
ALGORITHM:
Algo_Binary_Search (int a[], int x, int l, int h)
{
//a[] is the array to be searched from;
//l is the lower bound;
//h is the higher bound
if (l>h)
return -1;
m=(l+h)/2;

if

(a[m]=x)
return m;
if (a[m]>x)
return Binary_Search (a, x, l, m-1);
else
return Binary_Search (a, x, m+1, h);
}

C PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements:\n");
scanf("%d", &num);
printf("\nEnter the elements of list:\n");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0; high = num - 1;
printf("\nEnter element to be searched:\n");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1) {
printf("\nNumber present at %d", (position + 1));
} else
printf("\n The number is not present in the list");
return (0);
}
int binsearch(int a[], int x, int low, int high)
{ int mid;
if (low > high)
return -1;

mid = (low + high) / 2;


if (x == a[mid])
{
return (mid);
}
else if (x < a[mid]) {
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}

MERGE SORT BY DIVIDE AND CONQUER


ALGORITHM
PROBLEM STATEMENT:
Merge sort is an efficient, general-purpose, comparison-based
sorting technique based on divide and conquer algorithm. Most
implementations produce a stable sort, which means that the
implementation preserves the input order of equal elements in
the sorted output.
ALGORITHM:
Algo_Merge_Sort (low, high)
{
if (low<high)
{
mid=floor((low+high)/2);
Merge_Sort (low, mid);
Merge_Sort (mid+1, high);
Merge (low, mid, high);
}
}
Algo_Merge (low, mid, high)
{
//a[low:high] is a global array to be sorted;
//b[] is an auxillary global array
h=low;
i=low;
j=mid+1;
while ((l<=mid)and(j<=high)) do
{
if(a[h]<=a[j]) then

{
b[i]=a[j];
h=h+1;
}
else
{
b[i]=a[j];
j=j+1;
}
i=i+1;
}
if(h>mid) then
for k=j to high do
{
b[i]=a[k];
i=i+1;
}
else
for k=h to mid do
{
b[i]=a[k];
i=i+1;
}
for k = low to high do a[k] = b[k];
}
C PROGRAM:
#include<stdio.h>
#include<conio.h> int
a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;

if(low<high){
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k; h=low; i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else{ b[i]=a[j];
j++;
}
i++;
}
if(h>mid){
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else{

for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
int main()
{
int num,i;
printf("\nEnter the total numbers: ");
scanf("%d",&num);
printf("\nEnter %d numbers: \n",num);
for(i=1;i<=num;i++)
{
scanf("%d",&a[i]);
}
merge_sort(1,num);
printf("\nSORTED ORDER: \n");
for(i=1;i<=num;i++)
printf("\t%d",a[i]);
getch();
}

JOB SEQUENCING WITH DEADLINE BY GREEDY


ALGORITHM
PROBLEM STATEMENT:
Job sequencing with deadline problem consists of n jobs each
associated with a deadline and profit and our objective is to earn
maximum profit. The profit will be earned only when the said
job is completed on or before deadline. It is assumed that each
job will take unit time to complete.
ALGORITHM:
Algo_Greedy_Job_Sequencing (d, j, n)
{
j[i]=1; //include job 1 to get maximum profit
k=1; //indicates the number of jobs in j
for i=1 to n do
{

r=k;
//find position r after which i will be included in j[]
while ((d[j[r]]>d[i])and((d[j[r]]>r))
do r=r-1;
if((d[j[r]]>r)
{
//insert i into j[r+1]
for q=k to r+1 step -1 do

j[q+1]=j[q];
j[r+1]=i;
k=k+1;
}
}
return k;
}
C PROGRAM:
#include <stdio.h>
#define MAX 100
struct Job { int id;
int deadline;
int profit;
};
void jobSequencingWithDeadline(struct Job jobs[], int n);
int minValue(int x, int y) { if(x < y) return x;
return y;
}
void main() {
int i, j;
struct Job jobs[5];
for(i=0;i<5;i++){ printf("\nEnter
job ID: "); scanf("%d",&jobs[i].id);
printf("Enter job deadline: ");
scanf("%d",&jobs[i].deadline);
printf("Enter profit: ");
scanf("%d",&jobs[i].profit);
}
struct Job temp;
int n = 5;

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


for(j = 0; j < n - i; j++)
{
if(jobs[j+1].profit > jobs[j].profit)
{
temp = jobs[j+1];
jobs[j+1] = jobs[j];
jobs[j] = temp;
}
}
}
printf("\n%10s %10s %10s\n", "Job", "Deadline", "Profit");
for(i = 0; i < n; i++)
{
printf("%10i %10i %10i\n", jobs[i].id, jobs[i].deadline,
jobs[i].profit);
}
jobSequencingWithDeadline(jobs, n);
}
void jobSequencingWithDeadline(struct Job jobs[], int n)
{
int i, j, k, maxprofit;
int timeslot[MAX];
int filledTimeSlot = 0;
int dmax = 0;
for(i = 0; i < n; i++)
{
if(jobs[i].deadline > dmax)
{
dmax = jobs[i].deadline;

}
}
for(i = 1; i <= dmax; i++) {
timeslot[i] = -1;
}
printf("\nMaximum deadline: %d\n", dmax);
for(i = 1; i <= n; i++)
{
k = minValue(dmax, jobs[i - 1].deadline);
while(k >= 1) {
if(timeslot[k] == -1)
{
timeslot[k] = i-1;
filledTimeSlot++;
break;
}
k--;
}
if(filledTimeSlot == dmax) {
break;
}
}
printf("\nRequired Jobs: ");
for(i = 1; i <= dmax; i++)
{
printf("%d", jobs[timeslot[i]].id);
if(i < dmax)
{
printf(" --> ");
}

}
maxprofit = 0;
for(i = 1; i <= dmax; i++)
{
maxprofit += jobs[timeslot[i]].profit;
}
printf("\n\nMax Profit: %d\n", maxprofit);
}

15 PUZZLE PROBLEM BY BRANCH AND


BOUND ALGORITHM
PROBLEM STATEMENT:
The 15-puzzle is a sliding puzzle that consists of a frame of
numbered square tiles in random order with one tile missing.
The puzzle is called the 15-puzzle or 16-puzzle, respectively, for
the number of tiles and the number of spaces. The object of the
puzzle is to place the tiles in order by making sliding moves that
use the empty space.
ALGORITHM:
Algorithm LCSearch (t)
// Search t for an answer node
{
if (*t is an answer node) then output *t and return;
E=t; // E-node
Initialize the list of live nodes to be empty;
repeat
{
for (each child x of E) do
{
if (x is an answer node) then {output the path from x to t;
return};
Add(x); //Add x as new live node.
x->parent = E;
}
if (there are no more live nodes) then
{ write (No answer node); return;}
E=Least(); //Find new E-node with least cost from the queue of
live node.
} until(false);

}//End of Algorithm
C PROGRAM:
#include<stdio.h>
#include<conio.h>
int m=0,n=4;
int cal(int temp[10][10],int t[10][10])
{
int i,j,m=0;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
if(temp[i][j]!=t[i][j])
m++;
}
return m;
}
int check(int a[10][10],int t[10][10])
{
int i,j,f=1;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
if(a[i][j]!=t[i][j])
f=0;
return f;
}

void main()
{
int p,i,j,n=4,a[10][10],t[10][10],temp[10][10],r[10][10];

int m=0,x=0,y=0,d=1000,dmin=0,l=0;
clrscr();
printf("\nEnter the matrix to be solved,space with zero :\n");
for(i=0;i < n;i++)
for(j=0;j < n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the target matrix,space with zero :\n");
for(i=0;i < n;i++)
for(j=0;j < n;j++)
scanf("%d",&t[i][j]);
printf("\nEntered Matrix is :\n");
for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\nTarget Matrix is :\n");
for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",t[i][j]);
printf("\n");
}
while(!(check(a,t)))
{
l++;
d=1000;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{

if(a[i][j]==0)
{
x=i;
y=j;
}
}
//To move upwards
for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(x!=0)
{
p=temp[x][y];
temp[x][y]=temp[x-1][y];
temp[x-1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}
//To move downwards
for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(x!=n-1)
{
p=temp[x][y];

temp[x][y]=temp[x+1][y];
temp[x+1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}
//To move right side
for(i=0;i < n;i++)
for(j=0;j < n;j++)
temp[i][j]=a[i][j];
if(y!=n-1)
{
p=temp[x][y];
temp[x][y]=temp[x][y+1];
temp[x][y+1]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}
//To move left
for(i=0;i < n;i++)

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


temp[i][j]=a[i][j];
if(y!=0)
{
p=temp[x][y];
temp[x][y]=temp[x][y-1];
temp[x][y-1]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}
printf("\nCalculated Intermediate Matrix Value :\n");
for(i=0;i < n;i++)
{
for(j=0;j < n;j++)
printf("%d\t",r[i][j]);
printf("\n");
}
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
a[i][j]=r[i][j];
temp[i][j]=0;
}
printf("Minimum cost : %d\n",d);
}
getch();
}

FINDING MAXIMUM AND MINIMUM BY


DIVIDE AND CONQUER ALGORITHM
PROBLEM STATEMENT:
The problem required to find the elements with the maximum
and the minimum values in a given set or an array by divide and
conquer algorithm. The divide and conquer algorithm works by
recursively breaking down a problem into two or more
subproblems of the same or related type, until these become
simple enough to be solved directly.
ALGORITHM:
Algo_Max_Min (i,j,max,min)
{
/*a[1:n] is a global array; i,j are integers where 1<=i<=j<=n;
the largest and smallest values in a[1:n] will be set to max
and min respectively;*/
if (i=j) then
//small problem
max=min=a[i];
else
if (i=j-1) then
//small problem
{
if (a[i]<a[j]) then
{
max=a[j]; min=a[i];
}
else
{
max=a[i]; min=a[j];
}
}

else
{

//large problem
mid=(i+j)/2;
//solving sub-problems
Max_Min (i,mid,max,min);
Max_Min (mid+1,j,max1,min1);
//combining solutions
if(max<max1) then max=max1;
if(min>min1) then min=min1;

}
}
C PROGRAM:
#include<stdio.h> int
a[50],max,min; void
find(int i,int n){ int
mid,max1,min1; if(i==n)
max=min=a[i];
else
if(i==n-1)
if(a[i]<=a[n])
{
max=a[n];
min=a[i];
}
else
{
max=a[i];
min=a[n];
}
else{

mid=(i+n)/2;
find(i,mid);
max1=max;
min1=min;
find(mid+1,n);
if(max<max1)
max=max1;
if(min>min1) min=min1;
}
}
int main()
{
int i,n;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements in the array:\n\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=min=a[0];
find(0,n-1);
printf("\nMinimum: %d",min);
printf("\nMaximum: %d",max);
return 0;
}

Vous aimerez peut-être aussi