普及模拟赛 R1 A 题解

· · 题解

简单模拟题,送分。

subtask1

没有空白字符,即文本中没有空格和换行。

根据题目定义,一个标题至少要有一个空格,所以答案总是 0

subtask2

只有一行,答案要么是 0 要么是 1,随机一个即可。

一个满足要求的标题总是由如下要素构成:

按照顺序一个一个检查就可以了。还有一个问题在于,如何处理换行。

一个方法是在输入整数后读入一行。也可以使用 scanf("%d\n")。 某些快读可能能自动过滤后面一个字符,这也能解决这个问题。

以及,不推荐使用 gets(),这东西在 C++14 被橄榄了,到赛场上会 CE。

subtask3

把子任务 2 里面的方法每行做一遍就好了。

/* name: a
 * author: 5ab
 * created at: 22-07-24 19:52
 */
#include <iostream>
#include <string>
using namespace std;

typedef long long ll;

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, ans = 0;
    string s;

    cin >> n, getline(cin, s);
    for (int i = 0, j; i < n; i++)
    {
        getline(cin, s);

        j = 0;
        while (j < s.length() && s[j] == ' ')
            j++;
        if (j >= s.length() - 1 || s[j] != '#' || s[++j] != ' ')
            continue;
        while (j < s.length() && s[j] == ' ')
            j++;
        if (j >= s.length())
            continue;
        ans++;
    }

    cout << ans;

    return 0;
}

这道题也可以用正则表达式做,把标题的正则表达式一个一个写出来就可以了。

/* name: a
 * author: 5ab
 * created at: 22-07-24 19:52
 */
#include <iostream>
#include <string>
#include <regex>
using namespace std;

typedef long long ll;

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, ans = 0;
    string s;
    regex pattern(" *# +[a-z#].*");

    cin >> n, getline(cin, s);
    for (int i = 0, j; i < n; i++)
    {
        getline(cin, s);
        if (regex_match(s, pattern))
            ans++;
    }

    cout << ans;

    return 0;
}