As homework, I have the following program to create in java:
In the bookcase, we have a stack of N books that need to be copied manually by the authors of K. Each book has Ui pages, where Ai is a book.
We need to give each writer continuous books from the stack, and we cannot break the pages of the book.
Make a program that will give books for authors, but minimizing the maximum number of pages that the author copies.
As input, the user will give a string of numbers, where the first number is the number of books N, and the second number is the number of authors K, and the remaining numbers are the number of pages that are in each book.
As an output, the program will give the user the maximum number of pages that the record will copy.
Example:
Input: 15 6 30 40 10 40 50 20 30 40 10 70 10 50 30 50 10
Output: 90
In this example, the first script can take book1 = 30 and book2 = 40, but cannot take, for example, book1 = 30 with book3 = 10. In other words, you take books only from the top of the stack, without mixing them.
Here is my implementation:
import java.util.*;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> booksList = new LinkedList<Integer>();
System.out.printf("Give: ");
String answer = input.nextLine();
String[] arr = answer.split(" ");
for (String num : arr) {
booksList.add(Integer.parseInt(num));
}
int books = booksList.remove(0);
int writers = booksList.remove(0);
while (booksList.size() > writers) {
mergeMinimalPair(booksList);
}
System.out.println(getMax(booksList));
}
public static void mergeMinimalPair(List<Integer> books) {
int index = 0;
int minValue = books.get(0) + books.get(1);
for (int i = 1; i < books.size() - 1; i++) {
if ((books.get(i) + books.get(i + 1)) < minValue) {
index = i;
minValue = books.get(i) + books.get(i + 1);
}
}
combine(books, index, index + 1);
}
public static void combine(List<Integer> books, int indexA, int indexB) {
Integer a = books.get(indexA);
Integer b = books.get(indexB);
books.remove(indexB);
books.add(indexA, a + b);
books.remove(indexB);
}
public static int getMax(List<Integer> books) {
int max = books.get(0);
for (int i = 1; i < books.size(); i++) {
if (books.get(i) > max) {
max = books.get(i);
}
}
return max;
}
}
What I do, every time I combine a minimum pair of books, until the length of my list is equal to the number of authors, but it does not work, in the example, instead of 90, it gives 100.
I heard about dynamic programming solutions and Brutal solutions for knapsack problems, but at my university they have not yet taught us dynamic programming, so either the professor is embarrassed by what we know or he wants us to find a cruel solution.
, , - , , .
DP Brutal, DP, , DP.
EDIT: , -DP-,