You put side dishes into a fridge, and every time a day passes you throw away the ones that have gone bad. The dishes in the fridge sit in a single row of spots, and each dish has a number of days left during which it can be eaten. The first line gives the number of commands q, and the next q lines give one command each, in order. The command "put name d" puts a dish in. If that dish is not in the fridge, it goes into the last spot and its days left is d. If that dish is already in the fridge, d is added to its days left, and its spot does not change. The command "day" makes one day pass. The days left of every dish in the fridge go down by 1, and every dish whose days left becomes 0 is thrown away. A dish that was thrown away and is put in again later goes into the last spot, like a dish coming in for the first time. For each "day" command, print on one line the names of the dishes thrown away that day, in spot order, separated by single spaces. If no dish was thrown away that day, print "-" on that line. After all commands, print the number of dishes left in the fridge on one line. Then, for each remaining dish in spot order, print its name and days left on one line, separated by a single space. If no dish is left, print only 0. Try keeping the dishes in a dictionary from name to days left and walking the dictionary in insertion order.
Input
1 ≤ q ≤ 2,000. Each command is "put name d" or "day". Names have 1 to 10 lowercase English letters, and 1 ≤ d ≤ 100
Output
One line per "day" command (the thrown-away names, or -), then the number of remaining dishes, then one line per remaining dish (name daysleft), in spot order
Example 1 · stdin
8
put kimchi 3
put egg 1
put tofu 3
day
put egg 2
put kimchi 1
day
day
stdout
egg
-
tofu egg
1
kimchi 1
Example 2 · stdin
3
put milk 1
day
day
stdout
milk
-
0
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
Keep the days left in a dictionary (left[name] += d); when a day passes, walk the dictionary in insertion order, subtract 1, and remove a dish from the dictionary when it reaches 0. Trap one is removing while walking the dictionary. In Python, del left[name] inside for name in left: stops with RuntimeError: dictionary changed size during iteration, so copy the keys into a list first, as in for name in list(left):. In Java, calling left.remove(name) inside for (String name : left.keySet()) throws ConcurrentModificationException at the following next() (if you removed the last key there is no further next(), and the loop ends quietly), so walk entrySet().iterator() and remove with it.remove(). A JS/TS Map may be changed with delete while for...of walks it, and deleted entries do not come up again. A Craykon Keys is a newly made list, so you may Remove from the dict while walking that list. Trap two is the spot of a dish put in again after being thrown away. Only removing it from the dictionary and inserting it again sends it to the end (Python dict, JS/TS Map, Java LinkedHashMap, a Craykon dict). If you skip over dishes left at 0 days instead of removing them, the dish put in again returns to its old spot, and the third line of example 1 becomes egg tofu. The documentation of C# Dictionary promises no enumeration order. On the judge's .NET 8 the next new key reuses the slot a removed key left, so the same example prints egg tofu, but that is just how it is implemented, not a rule. So the C# solution does not rely on dictionary order: it writes the spot order in a separate List<string> and deletes the thrown-away names with RemoveAll after the walk. Trap three is the order of C++ maps. std::map walks in dictionary order of the names, and unordered_map in a scrambled order. So the C++ solution keeps a vector<pair<string, int>> in spot order and, after the walk, deletes all entries that reached 0 at once with remove_if and erase. C has no dictionary, so it writes the dishes in an array in spot order, searches from the front with strcmp, and when a day passes moves the remaining dishes forward to fill the gaps.
Pythonmain.py · 23 lines
import syslines = sys.stdin.read().split("\n")q = int(lines[0])left = {} # 반찬 → 남은 날. dict는 열쇠를 넣은 차례대로 돈다out = []for i in range(1, q + 1): cmd = lines[i].split() if cmd[0] == "put": name, d = cmd[1], int(cmd[2]) left[name] = left.get(name, 0) + d # 있으면 값만 바뀌고 자리는 그대로 else: thrown = [] for name in list(left): # 돌면서 del 하려면 열쇠를 목록으로 먼저 복사한다 left[name] -= 1 if left[name] == 0: del left[name] # 지워야 다시 넣을 때 맨 뒤로 간다 thrown.append(name) out.append(" ".join(thrown) if thrown else "-")out.append(str(len(left)))for name, d in left.items(): out.append(f"{name} {d}")print("\n".join(out))
JavaScriptmain.js · 27 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);// Map은 열쇠를 넣은 차례대로 돈다. 지운 열쇠를 다시 넣으면 맨 뒤로 간다const left = new Map();const out = [];for (let i = 1; i <= q; i++) { const cmd = lines[i].trim().split(" "); if (cmd[0] === "put") { const name = cmd[1]; left.set(name, (left.get(name) ?? 0) + Number(cmd[2])); } else { const thrown = []; // Map을 for...of로 돌면서 delete 해도 된다(지운 항목은 다시 나오지 않는다) for (const [name, d] of left) { if (d === 1) { left.delete(name); thrown.push(name); } else { left.set(name, d - 1); } } out.push(thrown.length > 0 ? thrown.join(" ") : "-"); }}out.push(String(left.size));for (const [name, d] of left) out.push(`${name} ${d}`);console.log(out.join("\n"));
TypeScriptmain.ts · 28 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);// Map은 열쇠를 넣은 차례대로 돈다. 지운 열쇠를 다시 넣으면 맨 뒤로 간다const left = new Map<string, number>();const out: string[] = [];for (let i = 1; i <= q; i++) { const cmd = lines[i].trim().split(" "); if (cmd[0] === "put") { const name = cmd[1]; left.set(name, (left.get(name) ?? 0) + Number(cmd[2])); } else { const thrown: string[] = []; // Map을 for...of로 돌면서 delete 해도 된다(지운 항목은 다시 나오지 않는다) for (const [name, d] of left) { if (d === 1) { left.delete(name); thrown.push(name); } else { left.set(name, d - 1); } } out.push(thrown.length > 0 ? thrown.join(" ") : "-"); }}out.push(String(left.size));for (const [name, d] of left) out.push(`${name} ${d}`);console.log(out.join("\n"));
JavaMain.java · 41 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(br.readLine().trim()); // LinkedHashMap은 넣은 차례를 지킨다. 지운 열쇠를 다시 넣으면 맨 뒤로 간다 Map<String, Integer> left = new LinkedHashMap<>(); StringBuilder out = new StringBuilder(); for (int i = 0; i < q; i++) { String[] cmd = br.readLine().trim().split(" "); if (cmd[0].equals("put")) { left.merge(cmd[1], Integer.parseInt(cmd[2]), Integer::sum); } else { List<String> thrown = new ArrayList<>(); // for-each 안에서 left.remove를 부르면 ConcurrentModificationException — 반복자의 remove로 뺀다 Iterator<Map.Entry<String, Integer>> it = left.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Integer> e = it.next(); if (e.getValue() == 1) { thrown.add(e.getKey()); it.remove(); } else { e.setValue(e.getValue() - 1); } } out.append(thrown.isEmpty() ? "-" : String.join(" ", thrown)).append('\n'); } } out.append(left.size()).append('\n'); for (Map.Entry<String, Integer> e : left.entrySet()) out.append(e.getKey()).append(' ').append(e.getValue()).append('\n'); System.out.print(out); }}
C#Main.cs · 48 lines
using System;using System.Collections.Generic;using System.Text;class Program{ static void Main() { int q = int.Parse(Console.ReadLine().Trim()); // Dictionary는 도는 차례를 약속하지 않는다(뺀 자리에 새 열쇠가 들어간다). 자리 차례는 목록에 따로 적는다 var left = new Dictionary<string, int>(); var order = new List<string>(); var sb = new StringBuilder(); for (int i = 0; i < q; i++) { string[] cmd = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); if (cmd[0] == "put") { string name = cmd[1]; int d = int.Parse(cmd[2]); if (left.TryGetValue(name, out int had)) left[name] = had + d; else { left[name] = d; order.Add(name); // 처음 들어오거나 버린 뒤 다시 들어오면 맨 뒤 자리 } } else { var thrown = new List<string>(); foreach (string name in order) { left[name]--; if (left[name] == 0) { left.Remove(name); thrown.Add(name); } } order.RemoveAll(name => !left.ContainsKey(name)); sb.Append(thrown.Count > 0 ? string.Join(" ", thrown) : "-").Append('\n'); } } sb.Append(order.Count).Append('\n'); foreach (string name in order) sb.Append(name).Append(' ').Append(left[name]).Append('\n'); Console.Write(sb); }}
C++main.cpp · 44 lines
#include <algorithm>#include <iostream>#include <string>#include <utility>#include <vector>int main() { std::ios::sync_with_stdio(false); int q; std::cin >> q; // std::map은 이름의 사전 순으로, unordered_map은 뒤섞인 차례로 돈다. 자리 차례대로 (이름, 남은 날)을 vector에 둔다 std::vector<std::pair<std::string, int>> left; std::string out; for (int i = 0; i < q; i++) { std::string cmd; std::cin >> cmd; if (cmd == "put") { std::string name; int d; std::cin >> name >> d; auto it = std::find_if(left.begin(), left.end(), [&](const auto& p) { return p.first == name; }); if (it != left.end()) it->second += d; else left.emplace_back(name, d); // 없으면(버린 뒤 다시 넣어도) 맨 뒤 } else { std::string thrown; for (auto& p : left) { if (--p.second == 0) { if (!thrown.empty()) thrown += ' '; thrown += p.first; } } // 도는 동안 지우지 않고, 다 돈 뒤 0이 된 것을 한꺼번에 지운다 left.erase(std::remove_if(left.begin(), left.end(), [](const auto& p) { return p.second == 0; }), left.end()); out += thrown.empty() ? "-" : thrown; out += '\n'; } } out += std::to_string(left.size()) + '\n'; for (const auto& p : left) out += p.first + ' ' + std::to_string(p.second) + '\n'; std::cout << out;}
Cmain.c · 51 lines
#include <stdio.h>#include <string.h>/* C에는 사전이 없어서, 자리 차례대로 이름과 남은 날을 배열에 적고 앞에서부터 찾는다 */#define MAXQ 2000static char name[MAXQ][11];static int left[MAXQ];static int count = 0;int main(void) { int q; char cmd[8], s[16]; scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%7s", cmd); if (strcmp(cmd, "put") == 0) { int d, k = -1; scanf("%15s %d", s, &d); for (int j = 0; j < count; j++) if (strcmp(name[j], s) == 0) { k = j; break; } if (k >= 0) { left[k] += d; } else { /* 없으면(버린 뒤 다시 넣어도) 맨 뒤 */ strcpy(name[count], s); left[count] = d; count++; } } else { int kept = 0, printed = 0; for (int j = 0; j < count; j++) { left[j]--; if (left[j] == 0) { printf(printed ? " %s" : "%s", name[j]); printed = 1; } else { /* 남는 반찬을 앞으로 당겨 빈자리를 메운다 */ if (kept != j) { strcpy(name[kept], name[j]); left[kept] = left[j]; } kept++; } } count = kept; printf(printed ? "\n" : "-\n"); } } printf("%d\n", count); for (int j = 0; j < count; j++) printf("%s %d\n", name[j], left[j]); return 0;}
Craykonmain.cray · 46 lines
q = Console.ReadLine().ToNumber();left = Dict(); // 반찬 → 남은 날. 열쇠목록은 넣은 차례다for (i = 0; i < q; i++){ cmd = Console.ReadLine().Trim().Split(" "); if (cmd[0] == "put") { name = cmd[1]; d = cmd[2].ToNumber(); if (left.Contains(name)) { left[name] = left[name] + d; // 값만 바뀌고 자리는 그대로 } else { left[name] = d; // 처음이거나 버린 뒤 다시 넣으면 맨 뒤 } } else { thrown = []; // 열쇠목록은 새로 만든 목록이라, 돌면서 사전에서 빼도 된다 foreach (name in left.Keys) { left[name] = left[name] - 1; if (left[name] == 0) { left.Remove(name); thrown.Add(name); } } if (thrown.Count > 0) { Console.WriteLine(thrown.Join(" ")); } else { Console.WriteLine("-"); } }}Console.WriteLine(left.Count);foreach (name in left.Keys){ Console.WriteLine(name + " " + left[name]);}