At a checkout, the codes of n items were scanned one by one.
The first line gives n, and the second line gives the n codes in scan order, separated by spaces.
A code is a string of 1 to 8 lowercase English letters and digits.
Codes are compared as strings exactly. So "007" and "7" are different codes.
For each distinct code, print one line with the code and how many times it was scanned, separated by one space.
The lines go in the order in which each code was first scanned.
Input
1 ≤ n ≤ 5,000, each code has 1 to 8 characters, lowercase letters (a-z) and digits (0-9)
Output
One line per distinct code (code, count), in order of first scan
Example 1 · stdin
6
milk 42 egg 7 42 milk
stdout
milk 2
42 2
egg 1
7 1
Example 2 · stdin
4
007 7 07 7
stdout
007 1
7 2
07 1
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
Counting needs just one dictionary: Python counts[c] = counts.get(c, 0) + 1, JS/TS Map with set(c, (get(c) ?? 0) + 1), Java merge(c, 1, Integer::sum), C# TryGetValue, C++ counts[c]++ (a missing key starts at 0), Craykon Dict() with Contains. The trap in this problem is the order when you loop. Python dict (since 3.7), JS/TS Map, Java LinkedHashMap and the Keys of a Craykon dict keep insertion order. Java HashMap and C++ unordered_map scramble the order, and C++ std::map goes in dictionary order of the keys. C# Dictionary seems to go in insertion order when nothing is removed, but the documentation does not promise it, so it is safer to write the first-seen codes in a separate list. A JS object {} is a trap too. Keys that read as non-negative integers without leading zeros, like "42", come first in increasing order, whatever order they were added in ("007" does not). Also, reading with the usual .split(/\s+/).map(Number) in JS/TS turns "007" into 7 and every letter code into NaN, so keep codes as strings. C has no dictionary, so write codes in an array in first-seen order and search from the front with strcmp.
Pythonmain.py · 7 lines
n = int(input())counts = {}for code in input().split(): counts[code] = counts.get(code, 0) + 1# dict는 처음 넣은 차례를 지킨다(3.7부터 언어 규칙)for code, c in counts.items(): print(code, c)
JavaScriptmain.js · 9 lines
const [n, ...codes] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);// Map은 처음 넣은 차례를 지킨다. 객체 {}는 "42" 같은 숫자 열쇠를 앞으로 당긴다const counts = new Map();for (const code of codes) { counts.set(code, (counts.get(code) ?? 0) + 1);}const out = [];for (const [code, c] of counts) out.push(`${code} ${c}`);console.log(out.join("\n"));
TypeScriptmain.ts · 9 lines
import { readFileSync } from "node:fs";const [n, ...codes]: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map<string, number>();for (const code of codes) { counts.set(code, (counts.get(code) ?? 0) + 1);}const out: string[] = [];for (const [code, c] of counts) out.push(`${code} ${c}`);console.log(out.join("\n"));
JavaMain.java · 21 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.LinkedHashMap;import java.util.Map;public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); // HashMap은 차례가 뒤섞인다. LinkedHashMap이 넣은 차례를 지킨다 Map<String, Integer> counts = new LinkedHashMap<>(); for (String code : br.readLine().trim().split("\\s+")) { counts.merge(code, 1, Integer::sum); } StringBuilder out = new StringBuilder(); for (Map.Entry<String, Integer> e : counts.entrySet()) { out.append(e.getKey()).append(' ').append(e.getValue()).append('\n'); } System.out.print(out); }}
C#Main.cs · 29 lines
using System;using System.Collections.Generic;using System.Text;class Program{ static void Main() { Console.ReadLine(); // Dictionary의 차례는 문서가 약속하지 않으니, 처음 나온 차례를 목록에 따로 적는다 var counts = new Dictionary<string, int>(); var order = new List<string>(); foreach (string code in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries)) { if (counts.TryGetValue(code, out int c)) { counts[code] = c + 1; } else { counts[code] = 1; order.Add(code); } } var sb = new StringBuilder(); foreach (string code in order) sb.Append(code).Append(' ').Append(counts[code]).Append('\n'); Console.Write(sb); }}
C++main.cpp · 19 lines
#include <iostream>#include <string>#include <unordered_map>#include <vector>int main() { std::ios::sync_with_stdio(false); int n; std::cin >> n; // std::map은 열쇠 순으로, unordered_map은 뒤섞인 차례로 돈다. 처음 나온 차례는 따로 적는다 std::unordered_map<std::string, int> counts; std::vector<std::string> order; for (int i = 0; i < n; i++) { std::string code; std::cin >> code; if (counts[code]++ == 0) order.push_back(code); } for (const std::string& code : order) std::cout << code << " " << counts[code] << "\n";}
Cmain.c · 25 lines
#include <stdio.h>#include <string.h>/* C에는 사전이 없어서, 처음 나온 차례대로 코드와 개수를 배열에 적고 찾을 때는 앞에서부터 훑는다 */static char names[5000][9];static int counts[5000];int main(void) { int n, kinds = 0; char code[16]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%15s", code); int j = 0; while (j < kinds && strcmp(names[j], code) != 0) j++; if (j == kinds) { strcpy(names[kinds], code); counts[kinds] = 0; kinds++; } counts[j]++; } for (int j = 0; j < kinds; j++) printf("%s %d\n", names[j], counts[j]); return 0;}
Craykonmain.cray · 16 lines
n = Console.ReadLine().ToNumber();codes = Console.ReadLine().Trim().Split(" ");counts = Dict();foreach (code in codes){ if (!counts.Contains(code)) { counts[code] = 0; } counts[code] = counts[code] + 1;}// 크레이콘 사전의 열쇠목록은 처음 넣은 차례다foreach (code in counts.Keys){ Console.WriteLine(code + " " + counts[code]);}