跳到正文

题解

题解:P10815 【模板】快速读入

StarHigh约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年7月29日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
7
题目
P10815

版本

  1. v1当前

题意解析:不用多说,把 nn 个数加起来输出。

很多人可能像我一样,拿到题直接写,结果75pts,但是请看看题目:【模板】快速读入。

快读就是提高读入速度的一种函数,代码如下:

C++
int read () {
    int x = 0, f = 1;//x用来记录大小,f用来判断负数。
    char c = getchar ();//读入字符
    while (c < '0' || c > '9') {//判断非数字,因为负数第一个字符是-
        if (c == '-') f = -1; //判断是否是负数
        c = getchar ();//读入
    }
    while (c >= '0' && c <= '9') {//判断是数字的情况
        x = x * 10 + (c - '0');//先增加一个数位,再加上刚才读入的,补全那一位
        c = getchar ();//继续读入
    }
    return x * f;//最后算出这个数返回(f为1,整数情况不变,f为-1就变成负数)
}

这就是快读的代码,能有效帮助输入的速度

然后我们配上代码:

C++
#include <bits/stdc++.h>
using namespace std;
int n, a;
long long ans;
int read () {
    int x = 0, f = 1;
    char c = getchar ();
    while (c < '0' || c > '9') {
        if (c == '-') f = -1;
        c = getchar ();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + (c - '0');
        c = getchar ();
    }
    return x * f;
}
int main () {
    ios::sync_with_stdio (false);
    n = read ();
    for (int i = 1; i <= n; i ++) {
        a = read ();
        ans += a;
    }
    cout << ans;
}

结果还是75pts。

接下来就要介绍一下 getchar_unlocked

这个东西相比 getchar 效率要更高,但是在本地可能运行不了,但是它在洛谷上是可以的,把快读函数里的 getchar 改成 getchar_unlocked 就能过了

AC{\color{green} AC} Code{\color{green} Code}:

C++
#include <bits/stdc++.h>
using namespace std;
int n, a;
int ans;
int read () {
    int x = 0, f = 1;
    char c = getchar_unlocked ();
    while (c < '0' || c > '9') {
        if (c == '-') f = -1;
        c = getchar_unlocked ();
    }
    while (c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c - '0');
        c = getchar_unlocked ();
    }
    return x * f;
}
int main () {
    ios::sync_with_stdio (false);
    n = read ();
    while (n --) {
        a = read ();
        ans += a;
    }
    cout << ans;
}

这是本蒟蒻的第一篇题解,求管理员大大速速通过!!!