• 输入优化(输入外挂)


      有时候用输入挂并不只是为了效率,对于一些以行末为结束(即 ' ' 或 ' ')的若干个数据的读入,此时用输入挂来处理就显得很有必要了,以判断字符是否为 ' ' 或 ' ' 来结束输入,否则单用 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上的题目也不会太卡输入格式(应该没有那么变态的题吧),感觉也够用了。

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

  • 相关阅读:
    推荐体系算法总结
    Springboot 多模块调用,找不到注入的类
    LRU算法
    在SQLServer中连接另一个SQLServer库数据,在Oracle中连接另一个Oracle库数据,在SQL Server中连接Oracle数据,在Oracle中连接SQL Server数据
    用C#实现木马程序
    CSS filter 滤镜可视化配置
    微信小程序农历日期选择器 lunarpicker
    ms Sql 数据库出现 “提供的统计信息流已损坏”的解决办法。
    自制《要塞:十字军东征》无限金钱修改器
    c#+Winform实现自定义的“复制、粘贴”右键快捷菜单,多个控件共享使用一个右键菜单。
  • 原文地址:https://www.cnblogs.com/Newdawn/p/4724868.html
Copyright © 2020-2023  润新知