11.08.2023 Views

Sahil ada practical - 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

FACULTY OF ENGINEERING

Information technology

Analysis and Design of Algorithms

Practical 5

AIM: Implementation of a knapsack problem using dynamic programming.

Code:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int W, n;

int main() {

int w, i, l = 0, p, j;

time_t start, end;

double tc;

printf("Enter number of Items \n");

scanf("%d", &n);

printf("Enter maximum weight \n");

scanf("%d", &W);

int k[n + 1][W + 1], a[W], v[W], ks[W];

printf("Enter weights of Items \n");

a[0] = 0;

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

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

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

}

printf("Enter profits/values of Items \n");

v[0] = 0;

start = clock();

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

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

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

}

k[0][0] = 0;

for (w = 1; w <= W; w++)

k[0][w] = 0;

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

k[i][0] = 0;

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

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

if (a[i] <= w) {

if (v[i] + k[i - 1][w - a[i]] > k[i - 1][w]) {

k[i][w] = v[i] + k[i - 1][w - a[i]];

} else {

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

210570116504 Batch A Page no. 1


FACULTY OF ENGINEERING

Information technology

Analysis and Design of Algorithms

}

} else {

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

}

}

}

printf("\n\nP W i \t0 ");

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

printf("%d ", i);

}

printf("\n_____________________\n");

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

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

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

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

}

printf("\n");

}

i = n;

p = W;

int u = 0, x = 0;

while (i >= 0 && p >= 0) {

if (k[i][W] != k[i - 1][W]) {

ks[++l] = i;

p = p - a[i];

u = u + i;

x += v[i];

i = i - 1;

} else

i = i - 1;

}

ks[++l] = '\0';

l = 1;

printf("\nThe individual weights are ");

while (ks[l] != '\0') {

printf("%d ", ks[l]);

l++;

}

end = clock();

printf("\n\n");

printf("\n\nTotal weight to be carried in knapsack is %d \n\n", u);

printf("Total profit in knapsack is %d \n\n", x);

tc = (difftime(end, start) / CLOCKS_PER_SEC);

printf("\ntime efficiency is %lf", tc);

}

210570116504 Batch A Page no. 2


FACULTY OF ENGINEERING

Information technology

Analysis and Design of Algorithms

O/P

Time Complexity:

O(N*W)

210570116504 Batch A Page no. 3

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!