0% found this document useful (0 votes)
11 views16 pages

ADA Lab

Uploaded by

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

ADA Lab

Uploaded by

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

4.

write a program to perform knapsack problem using greedy technique


#include<stdio.h>
int main()
{
float
weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int n,i,j;
printf("Enter the number of items :");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter Weight and Profit for item[%d] :\n",i);
scanf("%f %f", &weight[i], &profit[i]);
}
printf("Enter the capacity of knapsack :\n");
scanf("%f",&capacity);

for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];

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


for (j = i + 1; j < n; 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;
}

printf("Knapsack problems using Greedy Algorithm:\n");


for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}

output:-
Enter the number of items :4
Enter Weight and Profit for item[0] :
2
12
Enter Weight and Profit for item[1] :
1
10
Enter Weight and Profit for item[2] :
3
20
Enter Weight and Profit for item[3] :
2
15
Enter the capacity of knapsack :
5
Knapsack problems using Greedy Algorithm:

The maximum value is :38.333332


--------------------------------

13.write a program to implement the backtracking algorithm for solving N queens.


// C program to solve N Queen Problem using backtracking
#define N 4
#include <stdbool.h>
#include <stdio.h>

// A utility function to print solution


void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(board[i][j])
printf("Q ");
else
printf(". ");
}
printf("\n");
}
}

// A utility function to check if a queen can be placed on board[row][col]. Note that this
// function is called when "col" queens are already placed in columns from 0 to col -1.
// So we need to check only left side for attacking queens
bool isSafe(int board[N][N], int row, int col)
{
int i, j;

// Check this row on left side


for (i = 0; i < col; i++)
if (board[row][i])
return false;

// Check upper diagonal on left side


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;

// Check lower diagonal on left side


for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}

// A recursive utility function to solve N // Queen problem


bool solveNQUtil(int board[N][N], int col)
{
// Base case: If all queens are placed then return true
if (col >= N)
return true;

// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++) {

// Check if the queen can be placed on board[i][col]


if (isSafe(board, i, col)) {

// Place this queen in board[i][col]


board[i][col] = 1;

// Recur to place rest of the queens


if (solveNQUtil(board, col + 1))
return true;

//If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col]
board[i][col] = 0; // BACKTRACK
}
}

// If the queen cannot be placed in any row in


// this column col then return false
return false;
}

// This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to
// solve the problem. It returns false if queens cannot be placed, otherwise, return true and
// prints placement of queens in the form of 1s . Please note that there may be more than one
// solutions, this function prints one of the feasible solutions.
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

// Driver program to test above function


int main()
{
solveNQ();
return 0;
}
OUTPUT:
..Q.
Q...
...Q
.Q..

Process returned 0 (0x0) execution time : 0.055 s

#include<stdio.h>
#include<conio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
for (i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\n\nSolution #%d:\n",count);
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q\t");
else printf("*\t");
}
printf("\n");
}
}
void queen(int n)
{
int k=1;
a[k]=0;
while(k!=0)
{
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
}
else k--;
}
}
void main()
{
int i,n;
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
getch();
}
Output:-
Enter the number of Queens
4

Solution #1:
* Q * *
* * * Q
Q * * *
* * Q *

Solution #2:
* * Q *
Q * * *
* * * Q
* Q * *

Total solutions=2
// WRITE A PROGRAM TO IMPLEMENT GREEDY ALGORITHM FOR JOB SEQUENCING WITH DEADLINES

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// A structure to represent a job


typedef struct Job {

char id; // Job Id


int dead; // Deadline of job
int profit; // Profit if job is over before or on
// deadline
} Job;

// This function is used for sorting all jobs according to


// profit
int compare(const void* a, const void* b)
{
Job* temp1 = (Job*)a;
Job* temp2 = (Job*)b;
return (temp2->profit - temp1->profit);
}

// Find minimum between two numbers.


int min(int num1, int num2)
{
return (num1 > num2) ? num2 : num1;
}

// Returns maximum profit from jobs


void printJobScheduling(Job arr[], int n)
{
// Sort all jobs according to decreasing order of profit
qsort(arr, n, sizeof(Job), compare);

int result[n]; // To store result (Sequence of jobs)


bool slot[n]; // To keep track of free time slots

// Initialize all slots to be free


for (int i = 0; i < n; i++)
slot[i] = false;

// Iterate through all given jobs


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

// Find a free slot for this job (Note that we start


// from the last possible slot)
for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) {

// Free slot found


if (slot[j] == false) {
result[j] = i; // Add this job to result
slot[j] = true; // Make this slot occupied
break;
}
}
}

// Print the result


for (int i = 0; i < n; i++)
if (slot[i])
printf("%c ", arr[result[i]].id);
}

// Driver's code
int main()
{
Job arr[] = { { 'a', 2, 100 },
{ 'b', 1, 19 },
{ 'c', 2, 27 },
{ 'd', 1, 25 },
{ 'e', 3, 15 } };
int n = sizeof(arr) / sizeof(arr[0]);
printf(
"Following is maximum profit sequence of jobs \n");

// Function call
printJobScheduling(arr, n);
return 0;
}

Output:-
Following is maximum profit sequence of jobs
cae
Process returned 0 (0x0) execution time : 0.100 s

OR
#include <stdio.h>
#define MAX 100
typedef struct Job
{
char id[5];
int deadline;
int profit;
} Job;

void jobSequencingWithDeadline(Job jobs[], int n);


int minValue(int x, int y)
{
if(x < y) return x;
return y;
}

int main(void)
{
//variables
int i, j;

//jobs with deadline and profit


Job jobs[5] = {
{"j1", 2, 60},
{"j2", 1, 100},
{"j3", 3, 20},
{"j4", 2, 40},
{"j5", 1, 20},
};

//temp
Job temp;

//number of jobs
int n = 5;

//sort the jobs profit wise in descending order


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("%10s %10s %10s\n", "Job", "Deadline", "Profit");


for(i = 0; i < n; i++)
{
printf("%10s %10i %10i\n", jobs[i].id, jobs[i].deadline, jobs[i].profit);
}

jobSequencingWithDeadline(jobs, n);
return 0;
}

void jobSequencingWithDeadline(Job jobs[], int n)


{
//variables
int i, j, k, maxprofit;

//free time slots


int timeslot[MAX];

//filled time slots


int filledTimeSlot = 0;

//find max deadline value


int dmax = 0;
for(i = 0; i < n; i++)
{
if(jobs[i].deadline > dmax)
{
dmax = jobs[i].deadline;
}
}

//free time slots initially set to -1 [-1 denotes EMPTY]


for(i = 1; i <= dmax; i++)
{
timeslot[i] = -1;
}

printf("dmax: %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 all time slots are filled then stop


if(filledTimeSlot == dmax)
{
break;
}
}

//required jobs
printf("\nRequired Jobs: ");
for(i = 1; i <= dmax; i++)
{
printf("%s", jobs[timeslot[i]].id);

if(i < dmax)


{
printf(" --> ");
}
}

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

Job Deadline Profit


j2 1 100
j1 2 60
j4 2 40
j3 3 20
j5 1 20
dmax: 3

Required Jobs: j2 --> j1 --> j3


Max Profit: 180

Process returned 0 (0x0) execution time : 0.221 s

Dynamic Programming > Optimal binary search tree > C


Program
#include<stdio.h>
#include<conio.h>
#define MAX 10

void main()
{

char ele[MAX][MAX];
int w[MAX][MAX], c[MAX][MAX], r[MAX][MAX], p[MAX], q[MAX];
int temp=0, root, min, min1, n;
int i,j,k,b;
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
printf("\n");
for(i=1; i <= n; i++)
{
printf("Enter the Element of %d:",i);
scanf("%d",&p[i]);
}

printf("\n");
for(i=0; i <= n; i++)
{
printf("Enter the Probability of %d:",i);
scanf("%d",&q[i]);
}
printf("W\t\tC\t\tR\n");
for(i=0; i <= n; i++)
{
for(j=0; j <= n; j++)
{
if(i == j)
{
w[i][j] = q[i];
c[i][j] = 0;
r[i][j] = 0;
printf("W[%d][%d]: %d\tC[%d][%d]: %d\tR[%d][%d]: %d\n",i,j,w[i][j],i,j,c[i][j],i,j,r[i][j]);
}
}

}
printf("\n");
for(b=0; b < n; b++)
{
for(i=0,j=b+1; j < n+1 && i < n+1; j++,i++)
{

if(i!=j && i < j)


{
w[i][j] = p[j] + q[j] + w[i][j-1];
min = 30000;
for(k = i+1; k <= j; k++)
{
min1 = c[i][k-1] + c[k][j] + w[i][j];
if(min > min1)
{
min = min1;
temp = k;
}
}
c[i][j] = min;
r[i][j] = temp;
}
printf("W[%d][%d]: %d\tC[%d][%d]: %d\tR[%d][%d]: %d\n",i,j,w[i][j],i,j,c[i][j],i,j,r[i][j]);

}
printf("\n");
}
printf("Minimum cost = %d\n",c[0][n]);
root = r[0][n];

printf("Root = %d \n",root);
getch();
}

/* Output
Enter the number of elements: 4

Enter the Element of 1: 3


Enter the Element of 2:3
Enter the Element of 3:1
Enter the Element of 4:1

Enter the Probability of 0:2


Enter the Probability of 1:3
Enter the Probability of 2:1
Enter the Probability of 3:1
Enter the Probability of 4:1
W C R
W[0][0]: 2 C[0][0]: 0 R[0][0]: 0
W[1][1]: 3 C[1][1]: 0 R[1][1]: 0
W[2][2]: 1 C[2][2]: 0 R[2][2]: 0
W[3][3]: 1 C[3][3]: 0 R[3][3]: 0
W[4][4]: 1 C[4][4]: 0 R[4][4]: 0

W[0][1]: 8 C[0][1]: 8 R[0][1]: 1


W[1][2]: 7 C[1][2]: 7 R[1][2]: 2
W[2][3]: 3 C[2][3]: 3 R[2][3]: 3
W[3][4]: 3 C[3][4]: 3 R[3][4]: 4

W[0][2]: 12 C[0][2]: 19 R[0][2]: 1


W[1][3]: 9 C[1][3]: 12 R[1][3]: 2
W[2][4]: 5 C[2][4]: 8 R[2][4]: 3
W[0][3]: 14 C[0][3]: 25 R[0][3]: 2
W[1][4]: 11 C[1][4]: 19 R[1][4]: 2

W[0][4]: 16 C[0][4]: 32 R[0][4]: 2

Minimum cost = 32
Root = 2

OR
// A naive recursive implementation of optimal binary
// search tree problem
#include <stdio.h>
#include <limits.h>

// A utility function to get sum of array elements


// freq[i] to freq[j]
int sum(int freq[], int i, int j);

// A recursive function to calculate cost of optimal


// binary search tree
int optCost(int freq[], int i, int j)
{
// Base cases
if (j < i) // no elements in this subarray
return 0;
if (j == i) // one element in this subarray
return freq[i];

// Get sum of freq[i], freq[i+1], ... freq[j]


int fsum = sum(freq, i, j);

// Initialize minimum value


int min = INT_MAX;

// One by one consider all elements as root and


// recursively find cost of the BST, compare the
// cost with min and update min if needed
for (int r = i; r <= j; ++r)
{
int cost = optCost(freq, i, r-1) +
optCost(freq, r+1, j);
if (cost < min)
min = cost;
}
// Return minimum value
return min + fsum;
}

// The main function that calculates minimum cost of


// a Binary Search Tree. It mainly uses optCost() to
// find the optimal cost.
int optimalSearchTree(int keys[], int freq[], int n)
{
// Here array keys[] is assumed to be sorted in
// increasing order. If keys[] is not sorted, then
// add code to sort keys, and rearrange freq[]
// accordingly.
return optCost(freq, 0, n-1);
}

// A utility function to get sum of array elements


// freq[i] to freq[j]
int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}

// Driver program to test above functions


int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}

OUTPUT:-
Cost of Optimal BST is 142
Process returned 0 (0x0) execution time : 0.047 s

You might also like