东方博宜(2052)深搜+快读快写

· · 算法·理论

想必各位大佬,深搜应该不需要讲解,主要说一下快读和快写

第一段为快读,sign表示正负,需要注意的是x=0,因为在read()这个自定义函数中,已经经定义了参数x, 所以下面不需要再写一个int了。x=x10+c-'0'就是将数字累计的一个过程,最后将x=sign,将x变为正/负数

template <typename T> void read(T&x)
{
    x=0;
    int sign=1;
    char ch;
    do{ch=getchar();if(ch=='-') sign=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();} while(isdigit(ch));
    x*=sign;
}

下面一段为快写

inline void write(int x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
}

inline是一个关键字用于声明内联函数,void表示函数的返回类型,而write()则是函数的名称

此上是快读与快写的代码

1.注意这种快读快写的方法只能使用于整数

举一个最简单个最基础的例子

#include<bits/stdc++.h>
using namespace std;
template <typename T> void read(T&x)
{
    x=0;
    int sign=1;
    char ch;
    do{ch=getchar();if(ch=='-') sign=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();} while(isdigit(ch));
    x*=sign;
}
inline void write(int x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
int main()
{

    int a,b;
    read(a),read(b);
    write(a+b);

    return 0;
}

这样加速了我们的代码的执行,提高了效率

对了,还有一点

ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);

快读快写与上面的代码,二选一即可