zoukankan      html  css  js  c++  java
  • 输入输出优化

     1 inline bool read(int &res)
     2 {
     3     char c;int f=0;
     4     c=getchar();
     5     if(c==EOF)    return false;
     6     while((c<'0'||c>'9')&&c!='-')
     7         c=getchar();
     8     if(c=='-')    f=1,res=0;
     9     else    res=c-'0';
    10     while((c=getchar())>='0'&&c<='9')
    11         res=res*10+c-'0';
    12     if(f)    res=-res;
    13     return true;
    14 }
    15 inline void out(int x)
    16 {
    17     if(x>9)    out(x/10);
    18     putchar(x%10+'0');
    19 }

    以下是输入测试:

     1 #include<stdio.h>
     2 const int N=1e8;
     3 int main()
     4 {
     5     freopen("data.in","w",stdout);
     6     for(int i=1;i<=N;i++)
     7         printf("%d
    ",i);
     8     printf("0
    ");
     9     return 0;
    10 }
    测试程序
     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<time.h> 
     4 inline void in(int &res)
     5 {
     6     char c;
     7     while((c=getchar())<'0'||c>'9');
     8     res=c-'0';
     9     while((c=getchar())>='0'&&c<='9')
    10         res=res*10+c-'0';
    11 }
    12 int main()
    13 {
    14     int x;
    15     freopen("data.in","r",stdin);
    16     freopen("gua.out","w",stdout);
    17     clock_t start=clock();
    18     while(1)
    19     {
    20         in(x);
    21         if(!x)    break;
    22     }
    23     clock_t end=clock();
    24     printf("%d
    ",end-start);
    25     return 0;
    26 }
    优化读入
     1 #include<stdio.h>
     2 #include<time.h>
     3 int main()
     4 {
     5     freopen("data.in","r",stdin);
     6     freopen("std.out","w",stdout);
     7     int x;
     8     clock_t start=clock();
     9     while(scanf("%d",&x)&&x);
    10     clock_t end=clock();
    11     printf("%d
    ",end-start);
    12     return 0;
    13 }
    标准读入
    数据数量级 外挂耗时 标准耗时
    1e4 1 3
    1e5 5 29
    1e6 55 182
    1e7 617 1733
    1e8 7004 18924

    大致的输入测试就是这样,笔者没有做过多的测试。但是相信结果已经很明朗了,在1e6以下(包括1e6),使用标准输入会更方便一些。若数据量在1e6以上,显然使用外挂输入会节省很多时间。

    输出笔者就不测了,有兴趣的同学们可以去试一下。不要忘记评论。

  • 相关阅读:
    剑指offer-二叉树的深度
    剑指offer-二叉树中和为某一值的路径
    剑指offer-数组中只出现一次的数字
    剑指offer-反转单词顺序列
    剑指offer-数字在排序数组中出现的次数
    剑指offer-第一个只出现一次的字符
    剑指offer-连续子数组的最大和
    剑指offer-数组中的逆序对
    CSS3滚动条美化,CSS3滚动条皮肤
    mouseover事件与mouseenter事件的区别
  • 原文地址:https://www.cnblogs.com/L-King/p/5452287.html
Copyright © 2011-2022 走看看