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 行
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 行
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 行
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 行
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 行
#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 行
#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 行
// 크레이콘에는 정렬된 컨테이너가 없어서, 목록을 늘 작은 것부터 두고 자리는 이분 탐색으로 찾는다// x 이상인 값이 처음 나오는 자리(모두 x보다 작으면 목록의 개수)아래경계(선반, x){ lo = 0; hi = 선반.個数; 間 (lo < hi) { mid = 数学.商(lo + hi, 2); もし (선반[mid] < x) { lo = mid + 1; } でなければ { hi = mid; } } 返す lo;}q = コンソール.行読み().数に();선반 = [];繰り返す (k = 0; k < q; k++){ 낱말 = コンソール.行読み().空白除去().分ける(" "); 명령 = 낱말[0]; s = 낱말[1].数に(); もし (명령 == "put") { 선반.挿入(아래경계(선반, s), s); // 정렬이 깨지지 않는 자리에 끼운다 } でなければ もし (명령 == "fit") { i = 아래경계(선반, s); もし (i == 선반.個数) { コンソール.書く("-"); } でなければ { コンソール.書く(선반[i]); 선반.位置で取り除く(i); // 그 자리의 상자 하나만 꺼낸다 } } でなければ もし (명령 == "scrap") { lo = 아래경계(선반, s); hi = 아래경계(선반, s + 1); // 크기는 정수라서 's+1 이상인 첫 자리'가 's보다 큰 첫 자리다 繰り返す (j = lo; j < hi; j++) { 선반.位置で取り除く(lo); // 같은 자리를 빼면 뒤의 것이 당겨져 온다 } コンソール.書く(hi - lo); } でなければ { b = 낱말[2].数に(); コンソール.書く(아래경계(선반, b + 1) - 아래경계(선반, s)); // b도 셈에 넣는다 }}もし (선반.個数 == 0){ コンソール.書く("-");}でなければ{ コンソール.書く(선반.つなぐ(" "));}