Submission #645902

#TimeUsernameProblemLanguageResultExecution timeMemory
645902ateacodeKnapsack (NOI18_knapsack)Java
37 / 100
1043 ms11512 KiB
import java.util.Arrays;
import java.util.Scanner;

class knapsack {
	public static void main(String[] args) {
		// maximal weight of S kg's
		// n items to choose from, each with a value v and quantity q.
		// complete search problem
		// two decisions for each item: 1. Put item in basket 2. Ignore item. Goal is to maximise value.
		// Suppose we know the maximum value for the subset of items n[0..i] 
		// We can figure out max value of subset of items n[0..i+1] because for the marginal
		// decision (do i put item i + 1 in basket), we can update the max value given the optimal decision.
		Scanner in = new Scanner(System.in);

		int maxWeight = in.nextInt();
		int numItems = in.nextInt();

		int[] values = new int[numItems]; 
		int[] weights = new int[numItems];
		int[] quantities = new int[numItems];
		
		for(int i = 0; i < numItems; ++i) {
			values[i] = in.nextInt();
			weights[i] = in.nextInt();
			quantities[i] = in.nextInt();
		}


		int[] maxValueGivenWeight = new int[maxWeight + 1];

		for(int i = 0; i < numItems; ++i) {
		       for(int q = 0; q < quantities[i]; ++q) {	
				// consider the subset of items from 0..i
				for(int curWeight = maxWeight; curWeight >= 0; --curWeight) {
					if(weights[i] <= curWeight) { 
						maxValueGivenWeight[curWeight] = Math.max(
								maxValueGivenWeight[curWeight],
							       	values[i] + maxValueGivenWeight[curWeight - weights[i]]
						);	
					}
				}
		       }
		}

		System.out.println(maxValueGivenWeight[maxWeight]);
	}
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...