{ }codelper
重复字符串字符串长度P0440

用编号和点线排好目录

把书的目录加上编号和点线,一行一行输出。
输入的第一行给出条目数 n 和行宽 W,用一个空格隔开。
输入接下来的 n 行,每个条目依次给出层级 d、页码 p 和标题,各用一个空格隔开。
标题是由英文字母和数字组成的单词用单个空格连接而成的字符串,所以标题里也可能有空格。
第一个条目的层级是 1,每个条目的层级最多比紧挨着的前一个条目大 1(变小多少都可以)。
层级 1 到 6 各有一个计数,开始时都是 0。
出现层级为 d 的条目时,把层级 d 的计数加 1,并把比 d 更深的层级(d + 1 ~ 6)的计数全部重置为 0。
该条目的编号是改完之后层级 1 到层级 d 的计数按顺序用 .
连接起来的字符串(例如 2.1.3)。
按输入顺序每个条目输出一行。
左边部分是 2 × (d − 1) 个空格、编号、一个空格、标题依次连接起来的字符串。
输出的一行是左边部分、一个空格、k 个点(.)、一个空格、页码 p 依次连接起来的。
k 是让整行长度正好为 W 的个数,即 W − (左边部分的长度) − (p 的位数) − 2。
但如果这样求出的值小于 3(包括 0 或负数),k 就是 3,这一行会比 W 长。

输入
1 ≤ n ≤ 1,000,10 ≤ W ≤ 100,1 ≤ d ≤ 6,1 ≤ p ≤ 9,999(整数,没有前导 0)。
页码不一定递增。
标题长度 1 ~ 50,只含英文字母、数字和空格,开头和结尾不是空格,也不会有两个连续的空格
输出
n 行
样例 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
样例 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
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

点的个数 k 是用减法求出的,所以可能是 0 或负数。
第一个示例的最后一行左边部分有 34 个字符,所以 30 − 34 − 2 − 2 = −8。
陷阱一:不和 3 比较就直接把这个值传给重复。
各语言的结果不同。
Python "." * -8 会悄悄变成空字符串,C 用 for 调用 putchar k 次,所以什么也不输出就过去了。
两者都没有报错,却输出错误的行。
JS·TS ".".repeat(-8) 抛出 RangeError,Java ".".repeat(-8) 抛出 IllegalArgumentException,C# new string('.', -8)·StringBuilder.Append('.', -8) 抛出 ArgumentOutOfRangeException。
C++ std::string(k, '.') 会把 −8 变成很大的 size_t 并抛出 std::length_error,Craykon ".".重复(-8) 会以“重复次数必须是不小于 0 的整数”的错误停下。
所以要先修正:Python max(k, 3),JS·TS·Java Math.max(k, 3),C# Math.Max(k, 3),C++ std::max(k, 3),C·Craykon 用 如果 (k < 3) 这样的条件语句。
0 ~ 2 时也要增加到 3 个,只挡住负数是不够的。
陷阱二:增加层级 d 的计数时如果不把更深层级的计数重置为 0,第一个示例的 Values 会变成 2.3 而不是 2.1。
陷阱三:如果把编号长度当成每层一位、按 2d − 1 计算,第二个示例的 10 J 和 10.1 Ja 两行会各多一个点(最后一行反正要补到 3 个,所以不变)。
要先把编号做成字符串再量长度。
C 把 sprintf 返回的字符数加起来。
陷阱四:缩进的 2 × (d − 1) 个空格也算在行长度里。
漏掉的话,像第一个示例的 1.1 Why read 这样缩进的行会多出 2 × (d − 1) 个点(像最后一行那样补到 3 个的行不变)。
陷阱五:标题里也有空格,如果按每个空格切开、只取第三段,Why read 会被截成 Why。
要限定切分的段数:Python split(" ", 2),Java split(" ", 3),C# Split(' ', 3)。
JS·TS 的 split(" ", 3) 会丢掉剩下的部分,所以用 indexOf 找空格位置再截取。
C 先 scanf("%d %d ") 再 fgets,C++ 用两次 >> 并读掉一个空格后调用 std::getline,Craykon 用 分割(" ") 切开后用 子列表(2, 段.数量 - 2).连接(" ") 把标题重新连起来。
重复同一字符:Python "." * k,JS·TS·Java ".".repeat(k),C# new string('.', k),C++ std::string(k, '.'),Craykon ".".重复(k)。

Pythonmain.py · 18 行
import sys lines = 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 行
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 行
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 行
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 行
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 行
#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 行
#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 行
첫줄 = 控制台.读行().去空白().分割(" ");n = 첫줄[0].转数字();w = 첫줄[1].转数字();번호 = 新列表(7, 0); // 번호[d]: 단계 d에서 지금까지 센 번호循环 (i = 0; i < n; i += 1){    조각 = 控制台.读行().去空白().分割(" ");    d = 조각[0].转数字();    쪽 = 조각[1];    제목 = 조각.子列表(2, 조각.数量 - 2).连接(" "); // 제목 안의 빈칸을 되살린다    번호[d] += 1;    循环 (j = d + 1; j <= 6; j += 1)    {        번호[j] = 0; // 더 깊은 단계는 1부터 다시 센다    }    번호글 = "" + 번호[1];    循环 (j = 2; j <= d; j += 1)    {        번호글 = 번호글 + "." + 번호[j];    }    왼쪽 = " ".重复(2 * (d - 1)) + 번호글 + " " + 제목;    k = w - 왼쪽.长度 - 쪽.长度 - 2;    如果 (k < 3)    {        k = 3; // 음수를 되풀이에 넘기면 멈춘다. 모자라도 점은 3개    }    控制台.输出(왼쪽 + " " + ".".重复(k) + " " + 쪽);}