A packaging shop keeps empty boxes on a shelf. At first the shelf is empty. Each box has an integer size written on it, and several boxes may have the same size. q commands are given in order. There are four kinds of command. "put s" puts one box of size s on the shelf. This command prints nothing. "fit s" takes down one box whose size is the smallest among the boxes on the shelf with size at least s, and prints that box's size. If there are several such boxes, it takes down only one of them. If no box has size at least s, it prints - (a single minus sign) and leaves the shelf as it is. "scrap s" takes down and throws away every box of size exactly s, and prints how many boxes were thrown away. If there are none, it prints 0. "count a b" prints how many boxes on the shelf have a size from a to b inclusive. The shelf does not change. After all commands, print on the last line the sizes of the boxes left on the shelf, smallest first, separated by single spaces. Write a size once for every box of that size. If no box is left, print -. If your language has a standard-library container that keeps values sorted while holding the same value many times (a multiset), try using it. Grading looks only at the output.
Input
The first line has q (1 ≤ q ≤ 3,000), then q lines each have one command. A single space separates the command name (put, fit, scrap, count) from the numbers and the numbers from each other. 1 ≤ s ≤ 1,000,000,000 and 1 ≤ a ≤ b ≤ 1,000,000,000. Numbers are written as plain digits without commas.
Output
One line for each fit, scrap and count command in order, then a last line with the sizes of the boxes left (or - if none). Print numbers as plain digits without commas.
Example 1 · stdin
15
put 5
put 3
put 5
put 8
put 5
count 3 5
fit 4
scrap 5
scrap 5
fit 9
put 8
fit 8
fit 1
fit 1
count 1 1000000000
stdout
4
5
2
0
-
8
3
8
0
-
Example 2 · stdin
5
put 10
put 9
put 100
put 10
count 9 10
stdout
3
9 10 10 100
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
Only C++ has a sorted multiset (a sorted container that holds the same value many times) in its standard library, so every other language imitates one in its own way. In C++ std::multiset<int>, lower_bound(s) gives the first box of size at least s, erase(it) removes just that one box, and erase(s) removes every box of size s and returns how many it removed. count is std::distance(lower_bound(a), upper_bound(b)) (these are set iterators, so it walks and counts one by one). Java has no multiset, so keep size → number of boxes in a TreeMap<Integer, Integer>: put with merge(s, 1, Integer::sum), find the smallest size at least s with ceilingKey(s), and take the range with both ends included with subMap(a, true, b, true). C# has no multiset either: keep the distinct sizes in a SortedSet<int> and the number of boxes per size in a Dictionary<int, int>, and find the fitting size with Min of GetViewBetween(s, int.MaxValue). Python's standard library has no sorted container, so use a sorted list with the bisect module. Insert with insort; the boxes of size s sit from bisect_left(shelf, s) up to just before bisect_right(shelf, s), so del shelf[lo:hi] removes them all at once. JavaScript, TypeScript, C and Craykon keep a sorted array (list) and write the binary search for "the first position at least s" themselves. Because sizes are integers, "the first position greater than s" is "the first position at least s + 1" (the C solution also writes a separate search for "the first position greater than s"). To insert and remove, use splice in JS/TS, memmove in C (the regions overlap, so memcpy is not allowed), and Insert / RemoveAt in Craykon. Inserting in the middle shifts everything behind it, but q ≤ 3,000 makes that fast enough. Nine traps: (1) In a C++ multiset, erasing by value as in erase(*it) removes every box of that size. In example 1, fit 4 takes down all three boxes of size 5, so the next scrap 5 prints 0 instead of 2. (2) Java TreeSet and C# SortedSet are sets, so they refuse the same size from the second time on (add / Add just return false, with no error). Example 1's count 3 5 becomes 2 instead of 4. (3) In Java or C#, if you only decrease the box count and do not remove a size whose count reached 0 from the map or set, the next ceilingKey / Min returns that size again although no box is left. The two fit 1 commands at the end of example 1 give 3, 3 instead of 3, 8. (4) Java TreeMap.remove(s) returns null for a key that was not there, so appending it directly prints null instead of 0 at the second scrap 5. (5) In C#, Min of an empty GetViewBetween range returns 0 without an error. If you do not check Count first, the fit 9 of example 1 takes 0 as the size and then stops with a KeyNotFoundException at counts[0]. (6) Python bisect_right(shelf, s) is the first position "greater" than s, so using it in fit skips a box of size exactly s. Example 1's fit 8 prints - instead of 8. (7) If you cut the right end of count at lower_bound(b) (Python bisect_left(shelf, b)), boxes of size exactly b are left out. Example 1's count 3 5 gives 1 instead of 4. To count up to b inclusive use upper_bound(b). (8) Python list.remove(s) and Craykon list.Remove(s) remove only one item equal to s. If you count the thrown-away boxes separately, that line is right but boxes stay behind, so the second scrap 5 of example 1 prints 1 instead of 0. (9) In JS/TS, push followed by sort() without a compare function converts numbers to strings before ordering them, so the last line of example 2 becomes 10 10 100 9 and count 9 10 gives 2 instead of 3. Write sort((x, y) => x - y).
Pythonmain.py · 29 lines
import sysfrom bisect import bisect_left, bisect_right, insortlines = sys.stdin.read().split("\n")q = int(lines[0])shelf = [] # 선반의 상자 크기를 늘 작은 것부터, 같은 크기도 모두 둔다out = []for line in lines[1:q + 1]: cmd, *args = line.split() if cmd == "put": insort(shelf, int(args[0])) # 정렬이 깨지지 않는 자리에 끼운다 elif cmd == "fit": s = int(args[0]) i = bisect_left(shelf, s) # s 이상인 상자가 처음 나오는 자리(s와 같은 크기도 포함) if i == len(shelf): out.append("-") else: out.append(str(shelf.pop(i))) # 그 자리의 상자 하나만 꺼낸다 elif cmd == "scrap": s = int(args[0]) lo = bisect_left(shelf, s) hi = bisect_right(shelf, s) # 크기가 s인 상자는 shelf[lo:hi]에 모여 있다 out.append(str(hi - lo)) del shelf[lo:hi] else: # count a b a, b = int(args[0]), int(args[1]) out.append(str(bisect_right(shelf, b) - bisect_left(shelf, a))) # b도 셈에 넣으므로 오른쪽은 bisect_rightout.append(" ".join(map(str, shelf)) if shelf else "-")print("\n".join(out))
JavaScriptmain.js · 37 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);// JavaScript에는 정렬된 컨테이너가 없어서, 배열을 늘 작은 것부터 두고 자리는 이분 탐색으로 찾는다const shelf = [];// x 이상인 값이 처음 나오는 자리(모두 x보다 작으면 shelf.length)function lowerBound(x) { let lo = 0; let hi = shelf.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (shelf[mid] < x) lo = mid + 1; else hi = mid; } return lo;}const out = [];for (let k = 1; k <= q; k++) { const [cmd, x, y] = lines[k].trim().split(" "); const s = Number(x); if (cmd === "put") { shelf.splice(lowerBound(s), 0, s); // 정렬이 깨지지 않는 자리에 끼운다 } else if (cmd === "fit") { const i = lowerBound(s); if (i === shelf.length) out.push("-"); else out.push(String(shelf.splice(i, 1)[0])); // 그 자리의 상자 하나만 꺼낸다 } else if (cmd === "scrap") { const lo = lowerBound(s); const hi = lowerBound(s + 1); // 크기는 정수라서 's+1 이상인 첫 자리'가 's보다 큰 첫 자리'다 shelf.splice(lo, hi - lo); out.push(String(hi - lo)); } else { const b = Number(y); out.push(String(lowerBound(b + 1) - lowerBound(s))); // b도 셈에 넣는다 }}out.push(shelf.length === 0 ? "-" : shelf.join(" "));console.log(out.join("\n"));
TypeScriptmain.ts · 38 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);// TypeScript에도 정렬된 컨테이너가 없어서, 배열을 늘 작은 것부터 두고 자리는 이분 탐색으로 찾는다const shelf: number[] = [];// x 이상인 값이 처음 나오는 자리(모두 x보다 작으면 shelf.length)function lowerBound(x: number): number { let lo = 0; let hi = shelf.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (shelf[mid] < x) lo = mid + 1; else hi = mid; } return lo;}const out: string[] = [];for (let k = 1; k <= q; k++) { const [cmd, x, y] = lines[k].trim().split(" "); const s = Number(x); if (cmd === "put") { shelf.splice(lowerBound(s), 0, s); // 정렬이 깨지지 않는 자리에 끼운다 } else if (cmd === "fit") { const i = lowerBound(s); if (i === shelf.length) out.push("-"); else out.push(String(shelf.splice(i, 1)[0])); // 그 자리의 상자 하나만 꺼낸다 } else if (cmd === "scrap") { const lo = lowerBound(s); const hi = lowerBound(s + 1); // 크기는 정수라서 's+1 이상인 첫 자리'가 's보다 큰 첫 자리'다 shelf.splice(lo, hi - lo); out.push(String(hi - lo)); } else { const b = Number(y); out.push(String(lowerBound(b + 1) - lowerBound(s))); // b도 셈에 넣는다 }}out.push(shelf.length === 0 ? "-" : shelf.join(" "));console.log(out.join("\n"));
JavaMain.java · 54 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Map;import java.util.StringJoiner;import java.util.TreeMap;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(in.readLine().trim()); // Java에는 멀티셋이 없어서, 크기 → 상자 수를 늘 정렬된 TreeMap에 둔다 TreeMap<Integer, Integer> shelf = new TreeMap<>(); StringBuilder out = new StringBuilder(); for (int k = 0; k < q; k++) { String[] w = in.readLine().trim().split(" "); int s = Integer.parseInt(w[1]); switch (w[0]) { case "put" -> shelf.merge(s, 1, Integer::sum); case "fit" -> { Integer size = shelf.ceilingKey(s); // s 이상인 크기 가운데 가장 작은 것, 없으면 null if (size == null) { out.append("-\n"); } else { out.append(size).append('\n'); int left = shelf.get(size) - 1; if (left == 0) shelf.remove(size); // 0개가 된 크기는 열쇠째 빼야 다음 ceilingKey에 안 걸린다 else shelf.put(size, left); } } case "scrap" -> { Integer removed = shelf.remove(s); // 없던 열쇠면 null out.append(removed == null ? 0 : removed).append('\n'); } default -> { int b = Integer.parseInt(w[2]); int total = 0; for (int c : shelf.subMap(s, true, b, true).values()) total += c; // 양 끝을 모두 넣는 구간 out.append(total).append('\n'); } } } if (shelf.isEmpty()) { out.append("-\n"); } else { StringJoiner line = new StringJoiner(" "); for (Map.Entry<Integer, Integer> e : shelf.entrySet()) { for (int i = 0; i < e.getValue(); i++) line.add(e.getKey().toString()); } out.append(line).append('\n'); } System.out.print(out); }}
C#Main.cs · 66 lines
using System;using System.Collections.Generic;using System.Text;class Program{ static void Main() { int q = int.Parse(Console.ReadLine()); // C#에는 멀티셋이 없어서, 서로 다른 크기는 SortedSet에, 크기마다 상자 수는 Dictionary에 둔다 var sizes = new SortedSet<int>(); var counts = new Dictionary<int, int>(); var sb = new StringBuilder(); for (int k = 0; k < q; k++) { string[] w = Console.ReadLine().Trim().Split(' '); int s = int.Parse(w[1]); switch (w[0]) { case "put": sizes.Add(s); // 이미 있는 크기면 아무 일도 하지 않는다(개수는 counts가 센다) counts[s] = counts.GetValueOrDefault(s) + 1; break; case "fit": { var view = sizes.GetViewBetween(s, int.MaxValue); // s 이상인 크기들 if (view.Count == 0) // 빈 구간의 Min은 0이라 Count를 먼저 본다 { sb.Append("-\n"); break; } int size = view.Min; sb.Append(size).Append('\n'); counts[size]--; if (counts[size] == 0) { counts.Remove(size); sizes.Remove(size); // 0개가 된 크기는 집합에서도 뺀다 } break; } case "scrap": { int removed = counts.GetValueOrDefault(s); counts.Remove(s); sizes.Remove(s); sb.Append(removed).Append('\n'); break; } default: { int b = int.Parse(w[2]); int total = 0; foreach (int size in sizes.GetViewBetween(s, b)) total += counts[size]; sb.Append(total).Append('\n'); break; } } } var rest = new List<string>(); foreach (int size in sizes) for (int i = 0; i < counts[size]; i++) rest.Add(size.ToString()); sb.Append(rest.Count == 0 ? "-" : string.Join(" ", rest)).Append('\n'); Console.Write(sb); }}
C++main.cpp · 53 lines
#include <iostream>#include <iterator>#include <set>#include <string>int main() { std::ios::sync_with_stdio(false); int q; std::cin >> q; std::multiset<int> shelf; // 늘 정렬되어 있고, 같은 크기도 여러 번 담는다 std::string out; for (int k = 0; k < q; k++) { std::string cmd; std::cin >> cmd; if (cmd == "put") { int s; std::cin >> s; shelf.insert(s); } else if (cmd == "fit") { int s; std::cin >> s; auto it = shelf.lower_bound(s); // s 이상인 첫 상자 if (it == shelf.end()) { out += "-\n"; } else { out += std::to_string(*it) + "\n"; shelf.erase(it); // 반복자로 지우면 그 상자 하나만 빠진다 } } else if (cmd == "scrap") { int s; std::cin >> s; // 값으로 지우면 그 값인 상자를 모두 지우고, 지운 개수를 돌려준다 out += std::to_string(shelf.erase(s)) + "\n"; } else { int a, b; std::cin >> a >> b; // [a 이상인 첫 자리, b보다 큰 첫 자리) 사이의 개수 out += std::to_string(std::distance(shelf.lower_bound(a), shelf.upper_bound(b))) + "\n"; } } if (shelf.empty()) { out += "-\n"; } else { bool first = true; for (int s : shelf) { if (!first) out += ' '; out += std::to_string(s); first = false; } out += '\n'; } std::cout << out;}
Cmain.c · 73 lines
#include <stdio.h>#include <string.h>/* C에는 컨테이너가 없어서, 배열을 늘 작은 것부터 두고 자리는 이분 탐색으로 찾는다 */static int shelf[3000];static int count = 0;/* x 이상인 값이 처음 나오는 자리(모두 x보다 작으면 count) */static int lower_bound(int x) { int lo = 0, hi = count; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (shelf[mid] < x) lo = mid + 1; else hi = mid; } return lo;}/* x보다 큰 값이 처음 나오는 자리 */static int upper_bound(int x) { int lo = 0, hi = count; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (shelf[mid] <= x) lo = mid + 1; else hi = mid; } return lo;}/* [lo, hi) 자리의 값을 빼고 뒤의 것을 당긴다. 겹치는 영역이라 memcpy가 아니라 memmove */static void remove_range(int lo, int hi) { memmove(&shelf[lo], &shelf[hi], (size_t)(count - hi) * sizeof shelf[0]); count -= hi - lo;}int main(void) { int q; scanf("%d", &q); for (int k = 0; k < q; k++) { char cmd[8]; int s; scanf("%7s %d", cmd, &s); if (strcmp(cmd, "put") == 0) { int i = upper_bound(s); memmove(&shelf[i + 1], &shelf[i], (size_t)(count - i) * sizeof shelf[0]); shelf[i] = s; count++; } else if (strcmp(cmd, "fit") == 0) { int i = lower_bound(s); if (i == count) { puts("-"); } else { printf("%d\n", shelf[i]); remove_range(i, i + 1); } } else if (strcmp(cmd, "scrap") == 0) { int lo = lower_bound(s), hi = upper_bound(s); printf("%d\n", hi - lo); remove_range(lo, hi); } else { int b; scanf("%d", &b); printf("%d\n", upper_bound(b) - lower_bound(s)); /* b도 셈에 넣는다 */ } } if (count == 0) { puts("-"); } else { for (int i = 0; i < count; i++) printf(i ? " %d" : "%d", shelf[i]); putchar('\n'); } return 0;}
Craykonmain.cray · 69 lines
// 크레이콘에는 정렬된 컨테이너가 없어서, 목록을 늘 작은 것부터 두고 자리는 이분 탐색으로 찾는다// x 이상인 값이 처음 나오는 자리(모두 x보다 작으면 목록의 개수)아래경계(선반, x){ lo = 0; hi = 선반.Count; while (lo < hi) { mid = Mathf.Quot(lo + hi, 2); if (선반[mid] < x) { lo = mid + 1; } else { hi = mid; } } return lo;}q = Console.ReadLine().ToNumber();선반 = [];for (k = 0; k < q; k++){ 낱말 = Console.ReadLine().Trim().Split(" "); 명령 = 낱말[0]; s = 낱말[1].ToNumber(); if (명령 == "put") { 선반.Insert(아래경계(선반, s), s); // 정렬이 깨지지 않는 자리에 끼운다 } else if (명령 == "fit") { i = 아래경계(선반, s); if (i == 선반.Count) { Console.WriteLine("-"); } else { Console.WriteLine(선반[i]); 선반.RemoveAt(i); // 그 자리의 상자 하나만 꺼낸다 } } else if (명령 == "scrap") { lo = 아래경계(선반, s); hi = 아래경계(선반, s + 1); // 크기는 정수라서 's+1 이상인 첫 자리'가 's보다 큰 첫 자리다 for (j = lo; j < hi; j++) { 선반.RemoveAt(lo); // 같은 자리를 빼면 뒤의 것이 당겨져 온다 } Console.WriteLine(hi - lo); } else { b = 낱말[2].ToNumber(); Console.WriteLine(아래경계(선반, b + 1) - 아래경계(선반, s)); // b도 셈에 넣는다 }}if (선반.Count == 0){ Console.WriteLine("-");}else{ Console.WriteLine(선반.Join(" "));}