Search
 
SCRIPT & CODE EXAMPLE
 

C

fractional knapsack problem in c

#include <stdio.h>

void main()
{
    int capacity, no_items, cur_weight, item;
    int used[10];
    float total_profit;
    int i;
    int weight[10];
    int value[10];

    printf("Enter the capacity of knapsack:
");
    scanf("%d", &capacity);

    printf("Enter the number of items:
");
    scanf("%d", &no_items);

    printf("Enter the weight and value of %d item:
", no_items);
    for (i = 0; i < no_items; i++)
    {
        printf("Weight[%d]:	", i);
        scanf("%d", &weight[i]);
        printf("Value[%d]:	", i);
        scanf("%d", &value[i]);
    }

    for (i = 0; i < no_items; ++i)
        used[i] = 0;

    cur_weight = capacity;
    while (cur_weight > 0)
    {
        item = -1;
        for (i = 0; i < no_items; ++i)
            if ((used[i] == 0) &&
                ((item == -1) || ((float) value[i] / weight[i] > (float) value[item] / weight[item])))
                item = i;

        used[item] = 1;
        cur_weight -= weight[item];
        total_profit += value[item];
        if (cur_weight >= 0)
            printf("Added object %d (%d Rs., %dKg) completely in the bag. Space left: %d.
", item + 1, value[item], weight[item], cur_weight);
        else
        {
            int item_percent = (int) ((1 + (float) cur_weight / weight[item]) * 100);
            printf("Added %d%% (%d Rs., %dKg) of object %d in the bag.
", item_percent, value[item], weight[item], item + 1);
            total_profit -= value[item];
            total_profit += (1 + (float)cur_weight / weight[item]) * value[item];
        }
    }

    printf("Filled the bag with objects worth %.2f Rs.
", total_profit);
}
Comment

PREVIOUS NEXT
Code Example
C :: xor swap 
C :: c print char 
C :: insertion sort c 
C :: c# for loop decrement 
C :: how make a character in c scanf 
C :: c program to find the factorial of a number 
C :: Hello world in C programming language 
C :: c printing char pointer 
C :: how to reverse a string in c 
C :: c convert char to int 
C :: addition.c 
C :: celsius to fahrenheit formula 
C :: c read file 
C :: star pattern in c 
C :: 2 dimensional array in c 
C :: c strstr 
C :: pointers to a function in c 
C :: selection sort c 
C :: what is c 
C :: c language float user input 
C :: absolute value of intel intrinsic 
C :: c to fahrenheit 
C :: how to join an array of strings c 
C :: print the name of a file c 
C :: functions in c programming 
C :: c pointers and arrays 
C :: c atoi atof 
C :: what happens if i acess a freed variable in c 
C :: C Character l/O 
C :: Uri/Beecrowd problem no - 1151 solution in C 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =