Print a book's table of contents, one line per entry, with section numbers and dot leaders. The first line of input gives the number of entries n and the line width W, separated by one space. Each of the next n lines of input gives an entry's level d, page number p and title, in this order, separated by single spaces. A title is words of English letters and digits joined by single spaces, so a title may itself contain spaces. The first entry has level 1, and each entry's level is at most 1 greater than the level of the entry right before it (it may drop by any amount). Keep one counter for each level 1 to 6; all start at 0. When an entry of level d appears, add 1 to the counter of level d and reset the counters of all deeper levels (d + 1 to 6) to 0. After that change, the entry's number is the counters of levels 1 through d, in order, joined with . (for example 2.1.3). Print one line per entry in input order. The left part is 2 × (d − 1) spaces, the number, one space and the title, joined in this order. The printed line is the left part, one space, k dots (.), one space and the page number p, joined in this order. k is the count that makes the whole line exactly W characters long, that is W − (length of the left part) − (number of digits of p) − 2. However, if that value is less than 3 (including 0 or negative), k is 3, and that line is longer than W.
Input
1 ≤ n ≤ 1,000, 10 ≤ W ≤ 100, 1 ≤ d ≤ 6, 1 ≤ p ≤ 9,999 (integers, no leading zeros). Page numbers need not increase. A title has length 1 to 50 and uses only English letters, digits and spaces; it does not start or end with a space and never has two spaces in a row
Output
n lines
Example 1 · stdin
6 30
1 1 Intro
2 2 Why read
2 5 How to use
1 9 Basics
2 9 Values
3 12 Numbers and their shapes
stdout
1 Intro .................... 1
1.1 Why read ............. 2
1.2 How to use ........... 5
2 Basics ................... 9
2.1 Values ............... 9
2.1.1 Numbers and their shapes ... 12
Example 2 · stdin
12 18
1 1 A
1 2 B
1 3 C
1 4 D
1 5 E
1 6 F
1 7 G
1 8 H
1 9 I
1 10 J
2 10 Ja
3 11 Jb
stdout
1 A ............ 1
2 B ............ 2
3 C ............ 3
4 D ............ 4
5 E ............ 5
6 F ............ 6
7 G ............ 7
8 H ............ 8
9 I ............ 9
10 J .......... 10
10.1 Ja ..... 10
10.1.1 Jb ... 11
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
The dot count k comes from a subtraction, so it can be 0 or negative. In the first example the last line's left part is 34 characters, so 30 − 34 − 2 − 2 = −8. Trap 1: passing that value straight to repeat without comparing it with 3. Languages react differently. Python "." * -8 quietly gives an empty string, and C, which calls putchar k times in a for loop, prints nothing. Both print a wrong line with no error. JS/TS ".".repeat(-8) throws RangeError, Java ".".repeat(-8) throws IllegalArgumentException, and C# new string('.', -8) and StringBuilder.Append('.', -8) throw ArgumentOutOfRangeException. In C++ std::string(k, '.') turns −8 into a huge size_t and throws std::length_error, and Craykon ".".Repeat(-8) stops with an error saying the count must be a non-negative integer. So fix k first: Python max(k, 3), JS/TS/Java Math.max(k, 3), C# Math.Max(k, 3), C++ std::max(k, 3), and in C and Craykon an if (k < 3) check. Values 0 to 2 must also become 3, so guarding only negatives is not enough. Trap 2: if you don't reset the deeper counters when level d's counter goes up, Values in the first example becomes 2.3 instead of 2.1. Trap 3: if you count the number's length as 2d − 1 (one digit per level), the 10 J and 10.1 Ja lines in the second example get one extra dot (the last line is raised to 3 dots anyway, so it stays the same). Build the number as a string and measure it; in C, add up what sprintf returns. Trap 4: the 2 × (d − 1) indent spaces count toward the line length too. Leave them out and indented lines such as 1.1 Why read in the first example get 2 × (d − 1) extra dots (a line raised to 3 dots, like the last one, stays the same). Trap 5: titles contain spaces, so splitting the line at every space and taking only the third piece cuts Why read down to Why. Limit the number of pieces: Python split(" ", 2), Java split(" ", 3), C# Split(' ', 3). In JS/TS split(" ", 3) throws the rest away, so find the spaces with indexOf and slice. C reads scanf("%d %d ") and then fgets; C++ reads with >> twice, skips one space and calls std::getline; Craykon splits with Split(" ") and joins the title back with GetRange(2, pieces.Count - 2).Join(" "). Repeating one character is Python "." * k, JS/TS/Java ".".repeat(k), C# new string('.', k), C++ std::string(k, '.'), and Craykon ".".Repeat(k).
Pythonmain.py · 18 lines
import syslines = sys.stdin.read().split("\n")n, w = map(int, lines[0].split())count = [0] * 7 # count[d]: 단계 d에서 지금까지 센 번호out = []for i in range(1, n + 1): d, p, title = lines[i].rstrip("\r").split(" ", 2) d = int(d) count[d] += 1 for j in range(d + 1, 7): # 더 깊은 단계는 1부터 다시 센다 count[j] = 0 number = ".".join(str(count[j]) for j in range(1, d + 1)) left = " " * (d - 1) + number + " " + title k = w - len(left) - len(p) - 2 k = max(k, 3) # 모자라도 점은 3개 쓴다. 음수를 그냥 곱하면 빈 문자열이 된다 out.append(left + " " + "." * k + " " + p)print("\n".join(out))
JavaScriptmain.js · 20 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const [n, w] = lines[0].trim().split(" ").map(Number);const count = new Array(7).fill(0); // count[d]: 단계 d에서 지금까지 센 번호const out = [];for (let i = 1; i <= n; i++) { const line = lines[i].replace(/\r$/, ""); const a = line.indexOf(" "); const b = line.indexOf(" ", a + 1); const d = Number(line.slice(0, a)); const p = line.slice(a + 1, b); const title = line.slice(b + 1); count[d]++; for (let j = d + 1; j <= 6; j++) count[j] = 0; // 더 깊은 단계는 1부터 다시 센다 const number = count.slice(1, d + 1).join("."); const left = " ".repeat(d - 1) + number + " " + title; // 음수를 repeat에 넘기면 RangeError가 난다. 먼저 3과 견준다 const k = Math.max(w - left.length - p.length - 2, 3); out.push(left + " " + ".".repeat(k) + " " + p);}console.log(out.join("\n"));
TypeScriptmain.ts · 21 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const [n, w]: number[] = lines[0].trim().split(" ").map(Number);const count: number[] = new Array<number>(7).fill(0); // count[d]: 단계 d에서 지금까지 센 번호const out: string[] = [];for (let i = 1; i <= n; i++) { const line: string = lines[i].replace(/\r$/, ""); const a: number = line.indexOf(" "); const b: number = line.indexOf(" ", a + 1); const d: number = Number(line.slice(0, a)); const p: string = line.slice(a + 1, b); const title: string = line.slice(b + 1); count[d]++; for (let j = d + 1; j <= 6; j++) count[j] = 0; // 더 깊은 단계는 1부터 다시 센다 const num: string = count.slice(1, d + 1).join("."); const left: string = " ".repeat(d - 1) + num + " " + title; // 음수를 repeat에 넘기면 RangeError가 난다. 먼저 3과 견준다 const k: number = Math.max(w - left.length - p.length - 2, 3); out.push(left + " " + ".".repeat(k) + " " + p);}console.log(out.join("\n"));
JavaMain.java · 30 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] first = br.readLine().trim().split(" "); int n = Integer.parseInt(first[0]), w = Integer.parseInt(first[1]); int[] count = new int[7]; // count[d]: 단계 d에서 지금까지 센 번호 StringBuilder out = new StringBuilder(); for (int i = 0; i < n; i++) { String[] part = br.readLine().split(" ", 3); // 제목 안의 빈칸은 그대로 둔다 int d = Integer.parseInt(part[0]); String p = part[1], title = part[2]; count[d]++; for (int j = d + 1; j <= 6; j++) count[j] = 0; // 더 깊은 단계는 1부터 다시 센다 StringBuilder number = new StringBuilder(); for (int j = 1; j <= d; j++) { if (j > 1) number.append('.'); number.append(count[j]); } String left = " ".repeat(d - 1) + number + " " + title; // 음수를 repeat에 넘기면 IllegalArgumentException이 난다. 먼저 3과 견준다 int k = Math.max(w - left.length() - p.length() - 2, 3); out.append(left).append(' ').append(".".repeat(k)).append(' ').append(p).append('\n'); } System.out.print(out); }}
C#Main.cs · 27 lines
using System;using System.Text;class Program{ static void Main() { string[] first = Console.ReadLine().Trim().Split(' '); int n = int.Parse(first[0]), w = int.Parse(first[1]); var count = new int[7]; // count[d]: 단계 d에서 지금까지 센 번호 var sb = new StringBuilder(); for (int i = 0; i < n; i++) { string[] part = Console.ReadLine().TrimEnd('\r').Split(' ', 3); // 제목 안의 빈칸은 그대로 둔다 int d = int.Parse(part[0]); string p = part[1], title = part[2]; count[d]++; for (int j = d + 1; j <= 6; j++) count[j] = 0; // 더 깊은 단계는 1부터 다시 센다 string number = string.Join(".", count[1..(d + 1)]); // 단계 1 ~ d의 수 string left = new string(' ', 2 * (d - 1)) + number + " " + title; // 음수를 new string에 넘기면 ArgumentOutOfRangeException이 난다. 먼저 3과 견준다 int k = Math.Max(w - left.Length - p.Length - 2, 3); sb.Append(left).Append(' ').Append('.', k).Append(' ').Append(p).Append('\n'); } Console.Write(sb); }}
C++main.cpp · 29 lines
#include <algorithm>#include <iostream>#include <string>int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, w; std::cin >> n >> w; int count[7] = {0}; // count[d]: 단계 d에서 지금까지 센 번호 std::string out; for (int i = 0; i < n; i++) { int d; std::string p, title; std::cin >> d >> p; std::cin.get(); // 쪽 번호 뒤의 빈칸 하나 std::getline(std::cin, title); // 제목 안의 빈칸은 그대로 둔다 if (!title.empty() && title.back() == '\r') title.pop_back(); count[d]++; for (int j = d + 1; j <= 6; j++) count[j] = 0; // 더 깊은 단계는 1부터 다시 센다 std::string number = std::to_string(count[1]); for (int j = 2; j <= d; j++) number += "." + std::to_string(count[j]); std::string left = std::string(2 * (d - 1), ' ') + number + " " + title; // 음수를 std::string(k, '.')에 넘기면 size_t로 바뀌어 length_error가 난다. 먼저 3과 견준다 int k = std::max(w - (int)left.size() - (int)p.size() - 2, 3); out += left + " " + std::string(k, '.') + " " + p + "\n"; } std::cout << out;}
Cmain.c · 34 lines
#include <stdio.h>#include <string.h>int main(void) { int n, w; if (scanf("%d %d", &n, &w) != 2) return 0; int count[7] = {0}; /* count[d]: 단계 d에서 지금까지 센 번호 */ char title[64]; for (int i = 0; i < n; i++) { int d, p; scanf("%d %d ", &d, &p); fgets(title, sizeof title, stdin); /* 제목은 빈칸까지 줄 끝까지 읽는다 */ title[strcspn(title, "\r\n")] = '\0'; count[d]++; for (int j = d + 1; j <= 6; j++) count[j] = 0; /* 더 깊은 단계는 1부터 다시 센다 */ char left[128]; int len = 0; for (int j = 0; j < 2 * (d - 1); j++) left[len++] = ' '; for (int j = 1; j <= d; j++) { /* sprintf가 돌려주는 글자 수로 번호 길이를 센다(10 이상은 두 자리) */ len += sprintf(left + len, j > 1 ? ".%d" : "%d", count[j]); } len += sprintf(left + len, " %s", title); char page[8]; int plen = sprintf(page, "%d", p); int k = w - len - plen - 2; if (k < 3) k = 3; /* 모자라도 점은 3개 */ fputs(left, stdout); putchar(' '); for (int j = 0; j < k; j++) putchar('.'); printf(" %s\n", page); } return 0;}
Craykonmain.cray · 28 lines
첫줄 = Console.ReadLine().Trim().Split(" ");n = 첫줄[0].ToNumber();w = 첫줄[1].ToNumber();번호 = NewList(7, 0); // 번호[d]: 단계 d에서 지금까지 센 번호for (i = 0; i < n; i += 1){ 조각 = Console.ReadLine().Trim().Split(" "); d = 조각[0].ToNumber(); 쪽 = 조각[1]; 제목 = 조각.GetRange(2, 조각.Count - 2).Join(" "); // 제목 안의 빈칸을 되살린다 번호[d] += 1; for (j = d + 1; j <= 6; j += 1) { 번호[j] = 0; // 더 깊은 단계는 1부터 다시 센다 } 번호글 = "" + 번호[1]; for (j = 2; j <= d; j += 1) { 번호글 = 번호글 + "." + 번호[j]; } 왼쪽 = " ".Repeat(2 * (d - 1)) + 번호글 + " " + 제목; k = w - 왼쪽.Length - 쪽.Length - 2; if (k < 3) { k = 3; // 음수를 되풀이에 넘기면 멈춘다. 모자라도 점은 3개 } Console.WriteLine(왼쪽 + " " + ".".Repeat(k) + " " + 쪽);}