Untitled

 avatar
unknown
plain_text
9 months ago
1.8 kB
12
Indexable
#include <stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {
    float ans[20], tp = 0;
    int i, j, u;
    u = capacity;
    
    for (i = 0; i < n; i++)
        ans[i] = 0.0;
    

    for (i = 0; i < n; i++) {
        if (weight[i] > u)
            break;
        else {
            ans[i] = 1.0; 
            tp = tp + profit[i];
            u = u - weight[i];
        }
    }
    
    if (i < n) {
        ans[i] = u / weight[i];
        tp = tp + (ans[i] * profit[i]);
    }
    
    printf("\nanswer array: ");
    for (i = 0; i < n; i++)
        printf("%f\t", ans[i]);
    printf("\nMaximum profit: %f", tp);
}

int main() {
    float weight[20], profit[20], capacity;
    int num, i, j;
    float ratio[20], temp;
    
    printf("\nEnter n : ");
    scanf("%d", &num);
    
    printf("\nEnter the w and p : ");
    for (i = 0; i < num; i++) {
        scanf("%f %f", &weight[i], &profit[i]);
    }
    
    printf("\nEnter Bag size : ");
    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;
}
Editor is loading...
Leave a Comment