I have that task:
Assume that in addition to the scaling factor, there is a factor responsible for deallocating unnecessary memory after removing elements from the list. You will be given two factors: one for increasing and one for reducing the allocated memory. Following that will be queries for abstract addition and removal of clusters of elements. Your task is to return the allocated memory for each 'count' query at that moment.
Multiplication on a fraction is rounded up, division by a fraction is rounded down.
The initially allocated memory is 2.
Input: In the first line there's a number of queries and both the scaling (≥1.1) and downscaling (≥1.1) factors.
Following that are queries of these types: add count; remove count; count.
Output: For every 'count' query, write down the amount of allocated memory at the moment.
Input 1:
3 2.0 2.0
add 100
delete 50
count
Output 1:
64
Input 2:
12 1.1 1.1
add 10000
delete 500
count
add 255342
delete 255
count
add 243
delete 2435
count
add 666554
delete 346
count
Unfortunatelly, I don't know what output should be for test2. My code works correctly with test1, but it gets failed with test2. Can anyone help me? Maybe problem with rounding, may be not.
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int queryNumber = scanner.nextInt();
double upScalingFactor = scanner.nextDouble();
double downScalingFactor = scanner.nextDouble();
int allocatedMemory = 2;
int numOfElementsToStore = 0;
for (int i = 0; i < queryNumber; i++) {
String operationType = scanner.next();
switch (operationType) {
case "add":
int amountToAdd = scanner.nextInt();
numOfElementsToStore += amountToAdd;
while (allocatedMemory <= numOfElementsToStore) {
allocatedMemory = (int) Math.ceil(allocatedMemory * upScalingFactor);
}
break;
case "delete":
int amountToSubtract = scanner.nextInt();
numOfElementsToStore -= amountToSubtract;
while (Math.floor(allocatedMemory / downScalingFactor) >= numOfElementsToStore) {
allocatedMemory = (int) Math.floor(allocatedMemory / downScalingFactor);
}
break;
case "count":
System.out.println(allocatedMemory);
break;
}
}
}
}
You should not cast multiply/divide the result inside while loop. And always use Math.floor()
.
Correct output for input 2 :
9660
271469
271469
937184
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.