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

· · 题解

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

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

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

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就变成负数)
}

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

然后我们配上代码:

#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 就能过了

```cpp #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; } ``` 这是本蒟蒻的第一篇题解,求管理员大大速速通过!!!