P10815 【模板】快速读入
题目背景
制约解除作战!
题目描述
给你 n 个数,你需要求和并输出。
输入格式
第一行一个整数 n。
之后一行 n 个整数以空格隔开,表示给定的 n 个数。
输出格式
一行一个数表示给定的数的和。
输入输出样例
输入 #1复制
5 -1 2 -3 4 -5
输出 #1复制
-3
说明/提示
对于 25% 的数据,满足 n=10^5。
对于 25% 的数据,满足 n=10^6。
对于 25% 的数据,满足 n=10^7。
对于 25% 的数据,满足 n=10^8。
对于 100% 的数据,满足所有数在 [−n,n] 之间。
数据保证对于序列的任何前缀,这个前缀的和在 32 位有符号整形的存储范围内。
#include <bits/stdc++.h>
using namespace std;
int n, a;
int ans;
int read () {
int x = 0, f = 1;//x用来记录大小,f用来判断负数。
char c = getchar_unlocked ();//读入字符
while (c < '0' || c > '9') {//判断非数字,因为负数第一个字符是-
if (c == '-') f = -1; //判断是否是负数
c = getchar_unlocked ();//读入
}
while (c >= '0' && c <= '9') {//判断是数字的情况
x = x * 10 + (c - '0');//先增加一个数位,再加上刚才读入的,补全那一位
c = getchar_unlocked ();//继续读入
}
return x * f;//最后算出这个数返回(f为1,整数情况不变,f为-1就变成负数)
}
int main () {
ios::sync_with_stdio (false);
cin.tie(0);
n = read ();
while (n --) {
a = read ();
ans += a;
}
cout << ans;
}
奉上万能模板:
inline int read(){
int x = 0, f = 1;
char ch = getchar_unlocked();
while (!isdigit(ch)){
if (ch == '-')
f = -1;
ch = getchar_unlocked();
}
while (isdigit(ch)){
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar_unlocked();
}
return x * f;
}
inline void write(int x){
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
x = x * 10 + (ch - '0');
改成x = (x << 1) + (x << 3) + (ch ^ 48);
其中,
x << n
表示 x 的二进制向左移动 n 位空位补 0,相当于 x=x*2^n,(x << 1) + (x << 3)
相当于 x*10
把getchar()
改成getchar_unlocked()
,效率接近 fread。