Skip to main content

Fractional Knapsack

1. You are given a number n, representing the count of items.

2. You are given n numbers, representing the values of n items.

3. You are given n numbers, representing the weights of n items.

3. You are given a number "cap", which is the capacity of a bag you've.

4. You are required to calculate and print the maximum value that can be created in the bag without overflowing it's capacity.

Note1: Items can be added to the bag even partially. But you are not allowed to put same items again and again to the bag.


Input Format

A number n

v1 v2 .. n number of elements

w1 w2 .. n number of elements

A number cap

Output Format

A decimal number representing the maximum value that can be created in the bag without overflowing it's capacity

1. You are given a number n, representing the count of items.

2. You are given n numbers, representing the values of n items.

3. You are given n numbers, representing the weights of n items.

3. You are given a number "cap", which is the capacity of a bag you've.

4. You are required to calculate and print the maximum value that can be created in the bag without overflowing it's capacity.

Note: Items can be added to the bag even partially. But you are not allowed to put same items again and again to the bag.


Input Format

A number n

v1 v2 .. n number of elements

w1 w2 .. n number of elements

A number cap

Output Format

A decimal number representing the maximum value that can be created in the bag without overflowing it's capacity


Solution:

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int val[] = new int[n],wt[] = new int[n];
        for(int i=0;i<n;i++)
            val[i] = sc.nextInt();
        for(int i=0;i<n;i++)
            wt[i] = sc.nextInt();
        int cap = sc.nextInt();
        
        System.out.println(fractionalKnapsack(n,val,wt,cap));
    }
    
    public static double fractionalKnapsack(int n, int val[], int wt[], int cap){
        Item[] items = new Item[n];
        for(int i=0;i<n;i++){
            items[i] = new Item();
            items[i].val = val[i];
            items[i].wt = wt[i];
            items[i].ratio = val[i] / (double) wt[i];
        }
        
        Arrays.sort(items);
        
        int i = items.length-1;
        double cost = 0;
        
        while(i>=0 && cap > 0){
            if(items[i].wt<=cap){
                cost += items[i].val;
            }else{
                cost += cap * (items[i].ratio);
            }
            cap -= items[i].wt;
            --i;
        }
        
        return cost;
    }
    
    public static class Item implements Comparable<Item>{
        int val;
        int wt;
        double ratio;
        public int compareTo(Item o){
            if(this.ratio == o.ratio)
                return 0;
            else if(this.ratio > o.ratio)
                return +1;
            else return -1;
        }
    }
}

Comments

Must Read:

Web Technology HTML 5 HTML 2 | Quiz 1

 Web Technology       HTML 5            HTML 2               Quiz 1  

Programming using Java Hands On - Control Structures | Print Customer Details

Print Customer Details Help Mr.Ben who is a programmer, in developing a registration form on console. Customers will not just input data, but also view the details once he/she finishes the registration.  Sample Input 1: Enter your name:Jany Enter age:25 Enter gender:Female Hailing from:Mexico Sample Output 1: Welcome, Jany Age:25 Gender:Female City:Mexico Result Description Summary of tests *Note: All the test cases might not have same weightage +------------------------------+ | 5 tests run/ 5 tests passed | +------------------------------+

UNIX Introduction to Unix | Post-Quiz

 UNIX  Introduction to Unix  Post-Quiz  Feedback Congratulations! You have passed by securing more that 80%. Question  1 Correct Mark 1.00 out of 1.00 Flag question Question text  What is the default maximum number of processes that can exist in Unix? Select one: a.  unlimited b.   32768           c.   4096        d.  1024          Feedback Your answer is correct. The correct answer is:  32768         Question  2 Correct Mark 1.00 out of 1.00 Flag question Question text Single user mode shell has _____ prompt.  Select one: a.   $ Normal user  b.  % Admin user c.  ~ Home user d.  # Root user    Feedback Your answer is correct. The correct answer is: # Root user  Question  3 Correct Mark 1.00 out of 1.00 Flag question Question text Predict the output for the following...

Data Formats ( XML & JSON ) XML AND JSON | Generate XSD 2

  Generate XSD 2 Generate XSD for the following XML document <?xml version="1.0" encoding="UTF-8"?> <!--  <!DOCTYPE  hotels  SYSTEM "hotel.dtd"> --> <hotels> <hotel> <ID>1</ID> <Name> TAJ GANJ </Name> <Stars>3</Stars> <Facilities>Restaurant,Parking,Internet</Facilities> <Address>Taj Ganj,FFatehabad Road Agra Uttar Pradesh 282001</Address> <Type>budget</Type> <Available>true</Available> </hotel> <hotel> <ID>2</ID> <Name> TAJ EXOTICA </Name> <Stars>5</Stars> <Facilities>Indian therapies,Yoga and meditation,Spaindulges,Parking</Facilities> <Address>CalwaddoBenaulim, Salcete Goa 403716</Address> <Type>luxury</Type> <Available>false</Available> </hotel> <hotel> <ID>3</ID> <Name> VIVANTA by TAJ </Name> <Stars>3<...

Programming using Java Hands On - Control Structures | Print Username

  Print Username Jeffy, who is going to complete the higher education in this year needs to create a simple application which accept the name of a person and welcome them with a message along with their name. She wants to read the data using the class "Scanner". Implement this scenario using Java. Sample Input 1:   Enter the name: Johson Sample Output 1: Welcome Johnson. Sample Input 2:   Enter the name: Stain Polson Sample Output 2: Welcome Stain Polson. Result Description Summary of tests *Note: All the test cases might not have same weightage +------------------------------+ | 2 tests run/ 2 tests passed | +------------------------------+

RDBMS Data Definition Language | Create Sales_info table

  Write a query to create Sales_info with constraints mentioned. Refer the below schema  Result Description Summary of tests +------------------------------+ | 3 tests run / 3 test passed | +------------------------------+

RDBMS Data Definition Language | Create Distributor table

  Write a query to create Distributor table with constraints mentioned.  Refer the below schema  Result Description Summary of tests +------------------------------+ | 3 tests run / 3 test passed | +------------------------------+

Coin Change Permutations

 1. You are given a number n, representing the count of coins. 2. You are given n numbers, representing the denominations of n coins. 3. You are given a number "amt". 4. You are required to calculate and print the number of permutations of the n coins using which the       amount "amt" can be paid. Note 1: You have an infinite supply of each coin denomination i.e. same coin denomination can be                    used for many installments in payment of "amt" Note 2: You are required to find the count of permutations and not combinations i.e.                   2 + 2 + 3 = 7 and 2 + 3 + 2 = 7 and 3 + 2 + 2 = 7 are different permutations of same                    combination. You should treat them as 3 and not 1. Input Format A number n n1 n2 .. n number of elements A number amt Output Format A number representing the cou...

Data Formats ( XML & JSON ) XML AND JSON XML AND JSON | Quiz 2 & 3

Data Formats ( XML & JSON )  XML AND JSON  XML AND JSON Quiz 2 & 3  

Subscribe to Get's Answer by Email