读入优化和输出优化

前两天做牛客的题  才知道有这么个玩意。。。。。

果然还是太菜  大佬们打比赛是去切题  我是去认识新名词。。。。。。

题目也很直白  说了 

读入文件较大,请使用读入优化,本机调试时请使用文件输入输出

而且题目  也给出了优化写法 

可以直接用  非常良心

inline int read() {
    char c = getchar(); int x = 0, f = 1;
    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 a = read(), b = read();
cout << a + b;

自己到网上看了看    大佬的讲解博客传送门

这个东西  还是有一点用的

根据大佬的测试   每50万组数据读入优化要比scanf快0.1秒(100ms)

那么一百万组数据 就快了0.2秒了  相当不错

下面给出代码模板

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
void read(int &x){
    int f=1;//标记正负号
    x=0;//初始化
    char s=getchar();
    while(s<'0'||s>'9'){//读入符号
        if(s=='-') f=-1;
        s=getchar();
    }
    while(s>='0'&&s<='9'){//读入数字
        x=x*10+s-'0';
        s=getchar();
    }
    x*=f;
    return ;
}
void print(int x){
    if(x<0){
        putchar('-');x=-x;
    }
    if(x>9)  print(x/10);//这里是个递归  所以虽然是按照从数字末尾到开头的顺序处理
    putchar(x%10+'0');      //但是输出的时候会倒着输出 也就是正序
    return ;
}
int main(){
    int x;
    while(1){
        read(x);
        print(x);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/holly_Z_P_F/article/details/82633445