当我们考试时遇到大量的读入或者输出时,这些代码会耗费许多运行程序的时间,导致TL
本来 log2n 的算法因为读入被卡成线性的就太不划算了,所以我们这里要采用读入输出优化
getchar 和 putchar 是最快的读入输出方式,变量名尽量用一些不是很常用的,以免冲突
1 #include<cstdio>
2 #include<cstdlib>
3 #include<cstring>
4 #include<cmath>
5 #include<iostream>
6 #include<algorithm>
7 using namespace std;
8
9 inline int read()
10 {
11 char ch=getchar();
12 int re=0;
13 bool fl=1;
14 /*
15 if (ch=='-')
16 {
17 fl=0;
18 ch=getchar();
19 }
20 */
21 while (ch>='0'&&ch<='9')
22 {
23 re=re*10+ch-'0';
24 ch=getchar();
25 }
26 return fl?re:-re;
27 }
28 inline void write(int re)
29 {
30 /*
31 if (re<0)
32 {
33 putchar('-');
34 re=-re;
35 }
36 */
37 if (re>9) write(re/10);
38 putchar(re%10+'0');
39 }
40 int main()
41 {
42 int n=read(),i,a;
43 for (i=1;i<=n;i++)
44 {
45 a=read();
46 write(a);
47 putchar('\n');
48 }
49 return 0;
50 }
这里注释掉的是考虑负数的情况,许多情况用不上
还有许多题目的输出仅为一行或者很少的数据,我们可以不写输出优化
还要注明一点,inline也是一个函数优化,它相当于整个函数define,可以看做直接将代码粘贴到调用的地方,而不进行递归,对于小而调用频繁的函数可以使用
读入优化可以当一个模板背下来,其实自己写快的话也不过20秒的事
版权所有,转载请联系作者,违者必究
QQ:740929894
原文链接: https://www.cnblogs.com/hadilo/p/5894384.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/240830
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!