{ }codelper
读到输入结束P0438

数被空行分开的段落

给出一份写有文字的文档。
文档有多少行不会另外给出,所以必须一直读到输入结束。
文档的每一行,要么是一个字符都没有的空行,要么是用一个空格隔开、由英文小写字母组成的若干单词。
连续一行以上的非空行组成的一块叫作段落。
也就是说,段落是前后被空行、输入开头或输入结尾隔开的、最长的一块连续非空行。
连续出现多个空行也只是把段落隔开,只有空行不会形成段落。
第一行输出输入的行数(空行也算)和段落数,用一个空格隔开。
第二行按文档中出现的顺序,输出每个段落所含的单词数,用一个空格隔开。
如果一个段落都没有,第二行输出 -(一个减号)。

输入
输入有 1 到 2,000 行,行数不另外给出。
每行有 0~80 个字符。
非空行是用一个空格隔开、只由英文小写字母组成的单词,不以空格开头或结尾(所以没有只含空格的行)。
包括最后一行在内,每一行都以换行符结尾
输出
第一行是行数和段落数,第二行是每个段落的单词数(没有段落时输出 -)
样例 1 · stdin
the cat sat
on the mat

dogs bark


birds sing
loudly
stdout
8 3
6 2 3
样例 2 · stdin
hello world

stdout
3 1
2
main.py
输入(stdin)

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

$ 就绪

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

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

因为不给出行数,必须把“输入结束了”和“这是空行”当作两个不同的信号区分开。
Java 的 BufferedReader.readLine() 和 C# 的 Console.ReadLine() 遇到空行返回 "",输入结束时返回 null。
C++ 的 getline(cin, line) 遇到空行得到空字符串,输入结束时变为假,while (getline(cin, line)) 就停下。
Craykon 的 控制台.读行() 同样在空行返回 "",在结尾返回 空,所以用 当 (行 != 空) 循环。
Python 的 for raw in sys.stdin: 和 C 的 while (fgets(buf, sizeof buf, stdin)) 在结尾会自己停下,但拿到的行带着换行符,所以要用 raw.rstrip("\n")、buf[strcspn(buf, "\n")] = '\0' 去掉。
JS、TS 把输入整个读进来,再用 split("\n") 分开。
陷阱一:因为每一行都以换行符结尾,JS、TS 的 split("\n") 会在最后一个换行符后面多留下一个空字符串。
照样计数的话,示例 1 的第一行变成 9 3,所以要用 pop() 丢掉(末尾的空字符串不会形成段落,第二行仍然正确)。
陷阱二:如果不去掉 Python sys.stdin 的行或 C fgets 缓冲区里的换行符,空行就是 "\n" 而不是 "",看起来不像空行。
在示例 1 上,Python 把整份文档当成一个段落,输出 8 1 和 11(数空格的 C 解法会给每个空行多数一个单词,输出 14)。
陷阱三:C# 里常见的 while (!string.IsNullOrEmpty(line = Console.ReadLine())) 不仅在 null 时停下,遇到空行也会停下。
它在第一个空行就不再读取,示例 1 变成 2 1 和 6。
陷阱四:如果只在遇到空行时才结束一个段落,文档不以空行结尾时就会漏掉最后一个段落。
循环结束后要再结束一次,否则示例 1 变成 8 2 和 6 2。
陷阱五:每遇到一个空行就结束一个段落,连续空行的地方就会出现单词数为 0 的段落。
示例 1 变成 8 4 和 6 2 0 3,所以只在当前段落有单词时才结束它。

Pythonmain.py · 19 行
import sys lines = 0counts = []  # 문단마다 단어 수words = 0  # 지금 읽고 있는 문단의 단어 수(0이면 문단 밖)for raw in sys.stdin:  # 입력이 끝나면 반복이 저절로 멈춘다    line = raw.rstrip("\n")  # sys.stdin의 줄에는 줄 바꿈이 붙어 있다    lines += 1    if line == "":        if words > 0:  # 빈 줄이 문단을 닫는다            counts.append(words)            words = 0    else:        words += len(line.split())if words > 0:  # 입력이 빈 줄 없이 끝나면 마지막 문단을 여기서 닫는다    counts.append(words) print(lines, len(counts))print(" ".join(map(str, counts)) if counts else "-")
JavaScriptmain.js · 20 行
// 입력을 통째로 읽어 줄 바꿈으로 나눈다const lines = require("fs").readFileSync(0, "utf8").split("\n");lines.pop(); // 모든 줄이 줄 바꿈으로 끝나므로, 마지막 줄 바꿈 뒤에 생긴 빈 문자열을 버린다 const counts = [];let words = 0; // 지금 읽고 있는 문단의 단어 수(0이면 문단 밖)for (const line of lines) {  if (line === "") {    if (words > 0) {      counts.push(words);      words = 0;    }  } else {    words += line.split(" ").length;  }}if (words > 0) counts.push(words); // 빈 줄 없이 끝난 마지막 문단 console.log(`${lines.length} ${counts.length}`);console.log(counts.length > 0 ? counts.join(" ") : "-");
TypeScriptmain.ts · 22 行
import { readFileSync } from "node:fs"; // 입력을 통째로 읽어 줄 바꿈으로 나눈다const lines: string[] = readFileSync(0, "utf8").split("\n");lines.pop(); // 모든 줄이 줄 바꿈으로 끝나므로, 마지막 줄 바꿈 뒤에 생긴 빈 문자열을 버린다 const counts: number[] = [];let words = 0; // 지금 읽고 있는 문단의 단어 수(0이면 문단 밖)for (const line of lines) {  if (line === "") {    if (words > 0) {      counts.push(words);      words = 0;    }  } else {    words += line.split(" ").length;  }}if (words > 0) counts.push(words); // 빈 줄 없이 끝난 마지막 문단 console.log(`${lines.length} ${counts.length}`);console.log(counts.length > 0 ? counts.join(" ") : "-");
JavaMain.java · 37 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import java.util.StringJoiner; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        List<Integer> counts = new ArrayList<>();        int lines = 0, words = 0;        String line;        // 빈 줄은 ""로, 입력이 끝나면 null이 온다        while ((line = br.readLine()) != null) {            lines++;            if (line.isEmpty()) {                if (words > 0) {                    counts.add(words);                    words = 0;                }            } else {                words += line.split(" ").length;            }        }        if (words > 0) counts.add(words); // 빈 줄 없이 끝난 마지막 문단         System.out.println(lines + " " + counts.size());        if (counts.isEmpty()) {            System.out.println("-");        } else {            StringJoiner sj = new StringJoiner(" ");            for (int c : counts) sj.add(String.valueOf(c));            System.out.println(sj);        }    }}
C#Main.cs · 33 行
using System;using System.Collections.Generic; class Program{    static void Main()    {        var counts = new List<int>();        int lines = 0, words = 0;        string line;        // 빈 줄은 ""로, 입력이 끝나면 null이 온다        while ((line = Console.ReadLine()) != null)        {            lines++;            if (line == "")            {                if (words > 0)                {                    counts.Add(words);                    words = 0;                }            }            else            {                words += line.Split(' ').Length;            }        }        if (words > 0) counts.Add(words); // 빈 줄 없이 끝난 마지막 문단         Console.WriteLine($"{lines} {counts.Count}");        Console.WriteLine(counts.Count > 0 ? string.Join(" ", counts) : "-");    }}
C++main.cpp · 38 行
#include <iostream>#include <sstream>#include <string>#include <vector>using namespace std; int main() {    string line;    vector<int> counts;    int lines = 0, words = 0;    // getline은 줄 바꿈을 떼어 주고, 입력이 끝나면 거짓이 되어 반복이 멈춘다    while (getline(cin, line)) {        lines++;        if (line.empty()) {            if (words > 0) {                counts.push_back(words);                words = 0;            }        } else {            istringstream in(line);            string w;            while (in >> w) words++;        }    }    if (words > 0) counts.push_back(words); // 빈 줄 없이 끝난 마지막 문단     cout << lines << ' ' << counts.size() << '\n';    if (counts.empty()) {        cout << "-\n";    } else {        for (size_t i = 0; i < counts.size(); i++) {            if (i > 0) cout << ' ';            cout << counts[i];        }        cout << '\n';    }    return 0;}
Cmain.c · 36 行
#include <stdio.h>#include <string.h> int main(void) {    char buf[128];    static int counts[1000]; /* 문단은 많아야 1,000개 */    int lines = 0, paragraphs = 0, words = 0;    /* fgets는 입력이 끝나면 NULL을 준다 */    while (fgets(buf, sizeof buf, stdin)) {        buf[strcspn(buf, "\n")] = '\0'; /* fgets가 담아 준 줄 바꿈을 지운다 */        lines++;        if (buf[0] == '\0') {            if (words > 0) {                counts[paragraphs++] = words;                words = 0;            }        } else {            words++; /* 단어 수 = 빈칸 수 + 1 */            for (char *p = buf; *p; p++) {                if (*p == ' ') words++;            }        }    }    if (words > 0) counts[paragraphs++] = words; /* 빈 줄 없이 끝난 마지막 문단 */     printf("%d %d\n", lines, paragraphs);    if (paragraphs == 0) {        printf("-\n");    } else {        for (int i = 0; i < paragraphs; i++) {            printf(i == 0 ? "%d" : " %d", counts[i]);        }        printf("\n");    }    return 0;}
Craykonmain.cray · 40 行
줄수 = 0;문단 = []; // 문단마다 단어 수단어 = 0; // 지금 읽고 있는 문단의 단어 수(0이면 문단 밖)줄 = 控制台.读行(); // 빈 줄은 "", 입력이 끝나면 빈값当 (줄 != 空){    줄수 += 1;    如果 (줄 == "")    {        如果 (단어 > 0)        {            문단.添加(단어);            단어 = 0;        }    }    否则    {        단어 += 줄.分割(" ").数量;    }    줄 = 控制台.读行();}如果 (단어 > 0){    문단.添加(단어); // 빈 줄 없이 끝난 마지막 문단} 控制台.输出(줄수 + " " + 문단.数量);如果 (문단.数量 == 0){    控制台.输出("-");}否则{    결과 = "" + 문단[0];    循环 (i = 1; i < 문단.数量; i++)    {        결과 = 결과 + " " + 문단[i];    }    控制台.输出(결과);}