JustPaste.it

#include <stdio.h>
int n, W, w[10], v[10], x[10];
float ratio[10];

void sortItems() 
{
    int i, j, temp;
    float tempRatio;
    for(i = 1; i <= n; i++) 
    {
        ratio[i] = (float)v[i] / w[i];
    }
    for(i = 1; i <= n; i++) 
    {
        for(j = i + 1; j <= n; j++) 
        {
            if(ratio[i] < ratio[j]) 
            {
                tempRatio = ratio[i];
                ratio[i] = ratio[j];
                ratio[j] = tempRatio;
                temp = w[i];
                w[i] = w[j];
                w[j] = temp;
                temp = v[i];
                v[i] = v[j];
                v[j] = temp;
            }
        }
    }
}

void discreteKnapsack() 
{
    int i, totalWeight = 0, totalValue = 0;
    for(i = 1; i <= n; i++) 
    {
        if(totalWeight + w[i] <= W) 
        {
            totalWeight += w[i];
            totalValue += v[i];
            x[i] = 1;
        } 
        else 
        {
            x[i] = 0;
        }
    }
    printf("Selected items:\n");
    for(i = 1; i <= n; i++) 
    {
        if(x[i] == 1) 
        {
            printf("Item %d: Weight=%d, Value=%d\n", i, w[i], v[i]);
        }
    }
    printf("Total Weight: %d\n", totalWeight);
    printf("Total Value: %d\n", totalValue);
}

void continuousKnapsack() 
{
    int i, totalWeight = 0, remainingWeight;
    float totalValue = 0.0;
    for(i = 1; i <= n; i++) 
    {
        if(totalWeight + w[i] <= W) 
        {
            totalWeight += w[i];
            totalValue += v[i];
            x[i] = 1;
        } 
        else 
        {
            remainingWeight = W - totalWeight;
            totalValue += v[i] * ((float)remainingWeight / w[i]);
            printf("Item %d: Weight=%d, Partial Value = %f\n", i, remainingWeight, v[i] * ((float)remainingWeight / w[i]));
            break;
        }
    }
    printf("Selected items:\n");
    for(i = 1; i <= n; i++) 
    {
        if(x[i] == 1) 
        {
            printf("Item %d: Weight=%d, Value=%d\n", i, w[i], v[i]);
        }
    }
    printf("Total Weight: %d\n", W);
    printf("Total Value: %.2f\n", totalValue);
}

int main() 
{
    int i;
    printf("Enter number of objects\n");
    scanf("%d", &n);
    printf("Enter knapsack capacity\n");
    scanf("%d", &W);
    printf("Enter weights of the objects\n");
    for(i = 1; i <= n; i++) 
    {
        scanf("%d", &w[i]);
    }
    printf("Enter profits of the objects\n");
    for(i = 1; i <= n; i++) 
    {
        scanf("%d", &v[i]);
    }
    sortItems();
    for(i = 1; i <= n; i++) 
    {
        x[i] = 0;
    }
    discreteKnapsack();
    for(i = 1; i <= n; i++) 
    {
        x[i] = 0;
    }
    continuousKnapsack();
    return 0;
}