Advertisement
Vankata17

Backpack Algorithm

Nov 9th, 2020 (edited)
1,208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class BackpackAlgorithm {
  6.     public static void main(String[] args) {
  7.         Scanner scan = new Scanner(System.in);
  8.         int m = Integer.parseInt(scan.nextLine());
  9.         int n = Integer.parseInt(scan.nextLine());
  10.         int[] g = new int[n];
  11.  
  12.         int free;
  13.         for (int i = 0; i < n; i++) {
  14.             System.out.print("Insert an element: ");
  15.             g[i] = Integer.parseInt(scan.nextLine());
  16.             System.out.println();
  17.         }
  18.         for (int i = 0; i < g.length - 1; i++) {
  19.             for (int j = 0; j < g.length - 1 - i; j++) {
  20.                 if (g[j] < g[j + 1]) {
  21.                     free = g[j];
  22.                     g[j] = g[j + 1];
  23.                     g[j + 1] = free;
  24.  
  25.                 }
  26.             }
  27.  
  28.         }
  29.  
  30.         for (int i = 0; i < g.length - 1; i++) {
  31.             while (g[i] <= m && m >=0) {
  32.                 m -= g[i];
  33.                 System.out.println("Now used: " + g[i]);
  34.             }
  35.         }
  36.         if (m > 0) {
  37.             System.out.println("Rest: " + m);
  38.         }
  39.     }
  40. }
  41.  
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement