zoukankan      html  css  js  c++  java
  • 输入优化(输入外挂)

      有时候用输入挂并不只是为了效率,对于一些以行末为结束(即 ' ' 或 ' ')的若干个数据的读入,此时用输入挂来处理就显得很有必要了,以判断字符是否为 ' ' 或 ' ' 来结束输入,否则单用 scanf 的话无法达到上述效果。

    1. 先来一个单纯用于正数读入,并且题目已明确给出输入的整数的个数(即不用手动判断何时为输入结束)的输入挂:

     1 #include<cctype>
     2 template<typename T>
     3 inline void read(T &x) {
     4     x = 0;
     5     char ch = getchar();
     6     while(!isdigit(ch))    ch = getchar();
     7     while(isdigit(ch)) {
     8         x = x * 10 + (ch - '0');
     9         ch = getchar();
    10     }
    11 }

      感觉挺精简的。

    2. 然后是可以支持负数读入的输入挂:

     1 #include<cctype>
     2 template<typename T>
     3 inline void read2(T &x) {
     4     x = 0;
     5     bool nag = 0;
     6     char ch = getchar();
     7     while(!isdigit(ch) && ch != '-')    ch = getchar();
     8     if(ch == '-') {
     9         nag = 1;
    10         ch = getchar();
    11     }
    12     while(isdigit(ch)) {
    13         x = x * 10 + (ch - '0');
    14         ch = getchar();
    15     }
    16     if(nag)   x = -x;
    17 }

      在前面的基础上加了一个符号的标记信息而已。

    3. 接下来是支持负数读入和行末结束判断的输入挂,并且负数读入时符号和数字之间允许有空格:

     1 inline bool isline(const char &ch) {
     2     return ch == '
    ' || ch == '
    ';
     3 }
     4 
     5 #include<cctype>
     6 bool eol;
     7 template<typename T>
     8 inline void read3(T &x) {
     9     x = 0;
    10     bool nag = 0;
    11     eol = 0;
    12     char ch = getchar();
    13     while(!isdigit(ch) && ch != '-')    ch = getchar();
    14     if(ch == '-') {
    15         nag = 1;
    16         while(!isdigit(ch))    ch = getchar();
    17     }
    18     while(isdigit(ch)) {
    19         x = x * 10 + (ch - '0');
    20         ch = getchar();
    21     }
    22     if(nag == 1)   x = -x;
    23     if(isline(ch))    eol = 1;
    24 }

      比起第二个版本,增加了一个全局变量 eol (end of line) 来表示是否读入了换行符 ' ' 或 ' ',因为在主函数中要用这个来判断,所以就定义成了全局变量,如果用函数的返回值来作为换行符的判断的话,那最后一个读入的数据恐怕要另作处理了,感觉并不比这种方法方便,所以便使用全局变量了,并在每次读入时初始化 eol 为 0,在主函数中也有可能需要重置为 0,或许我这样的设计并不是最好的,但一般OJ上的题目也不会太卡输入格式(应该没有那么变态的题吧),感觉也够用了。

      初步测试过没问题,有些细节可适当增删。

  • 相关阅读:
    LightOJ 1132 Summing up Powers(矩阵快速幂)
    hdu 3804 Query on a tree (树链剖分+线段树)
    LightOJ 1052 String Growth && uva 12045 Fun with Strings (矩阵快速幂)
    uva 12304 2D Geometry 110 in 1! (Geometry)
    LA 3263 That Nice Euler Circuit (2D Geometry)
    2013 SCAUCPC Summary
    poj 3321 Apple Tree (Binary Index Tree)
    uva 11796 Dog Distance (几何+模拟)
    uva 11178 Morley's Theorem (2D Geometry)
    动手动脑
  • 原文地址:https://www.cnblogs.com/Newdawn/p/4724868.html
Copyright © 2011-2022 走看看