快读快写以及其他有用命名空间

· · 算法·理论

前言及声明

在算法竞赛中,一个强大的模板库可以显著提升我们的编码效率和代码健壮性。本文分享一套个人长期使用的C++竞赛模板,它集成了常用定义、数学函数、调试宏以及一个高效的快读快写模块,希望能为大家带来便利。

又借助了夸克AI

模板功能总览

#include <bits/stdc++.h>
using namespace std;
namespace typenames{
    using ll = long long;
    using ull = unsigned long long;
    #define null nullptr
    #define rng(x) x.begin(),x.end()
    #define fs(x) x.first,x.second
}
using namespace typenames;
namespace calc{
    const long double eps=1e-14;
    const double PI=acos(-1.0);
    template<class T>int chkmin(T &a,T b){return a>b?a=b,1:0;}
    template<class T>int chkmax(T &a,T b){return a<b?a=b,1:0;}
    template<class T>T pow2(T a){return a*a;}
    template<class T>T mmin(T a,T b){return a<b?a:b;}
    template<class T>T mmax(T a,T b){return a>b?a:b;}
    template<class T>T aabs(T a){return a<0?-a:a;}
    #define gcd(x,y) __gcd(x,y)
    #define nline cout << '\n'
    #define yes cout << "YES" << endl
    #define no cout << "NO" << endl
    #define BIT(x) (1LL << (x))
    #define ONES(x) __builtin_popcount(x)
    #define ONESLL(x) __builtin_popcountll(x)
    #define CLZ(x) __builtin_clz(x)
    #define CLZLL(x) __builtin_clzll(x)
    #define ODD(x) ((x) & 1)
    #define EVEN(x) (!ODD(x))
    #define inf (0x3f3f3f3f)
    #define llinf (9223372036854775808LL>>1)
    #define ullinf (18446744073709551615ULL >> 1)
    static ll lcm(ll a, ll b){return (a / gcd(a, b)) * b;}

    static ll qpow(ll base, ll exp, ll mod = LLONG_MAX){ll res = 1;base %= mod;
        while (exp > 0){if (exp & 1) res = (res * base) % mod;
        base = (base * base) % mod;exp>>= 1;}return res;}

    static bool is_prime(int n){if (n < 2) return false;if (n == 2) return true;
        if (n % 2 == 0) return false;for (int i = 3;i * i <= n;i += 2)
        if (n % i == 0) return false;return true;}
}
namespace IO{
    #define out cout
    #define in cin
    #define print(format, ...) printf(format, __VA_ARGS__)
    #define input(format, ...) scanf(format, __VA_ARGS__)
}
namespace debug{
    #define debug(fmt, ...) \
        fprintf(stderr, "[%s:%d] " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
    #define mst(a,b) memset(a,b,sizeof(a))
}

namespace fastIO {
    using namespace std;
    constexpr int IN_LEN = 1 << 20;
    constexpr int OUT_LEN = 1 << 20;

    char ibuf[IN_LEN], obuf[OUT_LEN];
    char *ih = ibuf, *it = ibuf + IN_LEN;
    char *oh = obuf;

    inline char gc() {
        if (ih == it) {
            ih = ibuf;
            it = ibuf + fread(ibuf, 1, IN_LEN, stdin);
            if (ih == it) return -1;
        }
        return *ih++;
    }

    inline void pc(char c) {
        if (oh == obuf + OUT_LEN) {
            fwrite(obuf, 1, OUT_LEN, stdout);
            oh = obuf;
        }
        *oh++ = c;
    }

    inline void flush() {
        fwrite(obuf, 1, oh - obuf, stdout);
        oh = obuf;
    }

    inline void space() { pc(' '); }
    inline void enter() { pc('\n'); }
    template<typename T> constexpr bool is_signed_v = 
    is_same_v<T, signed char> || is_same_v<T, short> ||
    is_same_v<T, int> || is_same_v<T, long> || is_same_v<T, long long>;

    template<typename T> constexpr bool is_unsigned_v = 
    !is_signed_v<T> && (is_same_v<T, char> || is_same_v<T, unsigned short> ||
    is_same_v<T, unsigned int> || is_same_v<T, unsigned long> 
    || is_same_v<T, unsigned long long>);

    template<typename T> struct is_container { constexpr static bool value = false; };
    template<typename T, typename A> struct is_container<vector<T, A>> 
    { constexpr static bool value = true; };
    template<typename T, size_t N> struct is_container<array<T, N>> 
    { constexpr static bool value = true; };
    template<typename T> struct is_container<set<T>> 
    { constexpr static bool value = true; };
    template<typename T> struct is_container<multiset<T>> 
    { constexpr static bool value = true; };
    template<typename K, typename V> struct is_container<map<K, V>> 
    { constexpr static bool value = true; };

    template<typename T>
    inline void read(T &x) {
        x = 0; 
        bool sign = false;
        char c = gc();

        while (c <= ' ' && c != -1) c = gc();
        if (c == -1) return;

        if (c == '-') {
            sign = true;
            c = gc();
        }
        if (!isdigit(c)) {
            x = 0;
            return;
        }

        while (isdigit(c)) { 
            x = x * 10 + (c ^ 48); 
            c = gc(); 
        }

        if constexpr (is_signed_v<T>) {
            if (sign) x = -x;
        }
    }

    inline void read(string &s) {
        s.clear();
        char c = gc();
        while (c <= ' ' && c != -1) c = gc();
        if (c == -1) return;
        while (c > ' ') { s += c; c = gc(); }
    }
    inline void read(char &c) {
        c = gc();
        while (c <= ' ') c = gc();
    }

    inline void read(double &x) {
        bool sign = false;
        char c = gc();
        while (c <= ' ' && c != -1) c = gc();
        if (c == -1) return;

        if (c == '-') {
            sign = true;
            c = gc();
        }

        x = 0.0;
        while (isdigit(c)) { 
            x = x * 10.0 + (c ^ 48); 
            c = gc(); 
        }

        if (c == '.') {
            c = gc();
            double frac = 0.1;
            while (isdigit(c)) { 
                x += (c ^ 48) * frac; 
                frac *= 0.1;
                c = gc(); 
            }
        }

        if (sign) x = -x;
    }

    template<typename T>
    inline void write(T x) {
        if constexpr (is_signed_v<T>) {
            if (x < 0) { pc('-'); x = -x; }
        }
        static char st[32];
        int top = 0;
        do { st[top++] = '0' + (x % 10); x /= 10; } while (x);
        while (top--) pc(st[top]);
    }

    template<typename T>
    inline void write(T x, int precision) {
        if (x < 0) { pc('-'); x = -x; }

        T eps = 0.5 * pow(10, -precision);
        x += eps;

        long long int_part = (long long)x;
        write<long long>(int_part);

        if (precision > 0) {
            pc('.');
            x -= int_part;
            long long frac_part = 1;
            for (int i = 0; i < precision; ++i) frac_part *= 10;

            long long frac_int = (long long)(x * frac_part + 0.5);

            int width = 0;
            long long tmp = frac_part / 10;
            while (tmp > frac_int && width < precision - 1) {
                pc('0');
                tmp /= 10;
                width++;
            }
            write<long long>(frac_int);
        }
    }
    template<typename T>
    inline void read(std::complex<T> &z) {
        T re, im;
        read(re); read(im);
        z = std::complex<T>(re, im);
    }

    template<typename T>
    inline void write(const std::complex<T> &z) {
        write(z.real()); space(); write(z.imag());
    }

    template<typename A> 
    struct is_container<vector<bool, A>> { constexpr static bool value = true; };

    inline void write(const char *s) { while (*s) pc(*s++); }
    inline void write(char c) { pc(c); }
    inline void write(bool b) { pc(b ? '1' : '0'); }
    inline void write(const string &s) { write(s.c_str()); }

    template<typename T>
    inline void write_container(const T &container) {
        bool first = true;
        for (const auto &item : container) {
            if (!first) space();
            first = false;
            write(item);
        }
    }

    template<typename T>
    inline void write(const T &val) {
        if constexpr (is_arithmetic_v<T>) {
            write(val);
        }
        else if constexpr (is_same_v<T, string>) {
            write(val.c_str());
        }
        else if constexpr (is_container<T>::value) {
            write_container(val);
        }
        else if constexpr (is_same_v<T, pair<typename T::first_type, 
        typename T::second_type>>) {
            write(val.first); space(); write(val.second);
        }
        else {
            printf("%s", to_string(val).c_str()); 
        }
    }

    template<typename T, typename... Args>
    inline void write(const T &first, const Args&... rest) {
        write(first);
        if constexpr (sizeof...(rest) > 0) {
            pc(' ');
            write(rest...);
        }
    }

    template<typename T1, typename T2>
    inline void read(pair<T1, T2> &p) {
        read(p.first);
        read(p.second);
    }

    template<typename T, size_t... Is>
    inline void read_tuple_impl(T &t, std::index_sequence<Is...>) {
        (void)std::initializer_list<int>{(read(std::get<Is>(t)), 0)...};
    }

    template<typename... Args>
    inline void read(std::tuple<Args...> &t) {
        read_tuple_impl(t, std::index_sequence_for<Args...>{});
    }

    template<typename T, size_t... Is>
    inline void write_tuple_impl(const T &t, std::index_sequence<Is...>) {
        constexpr size_t size = sizeof...(Is);
        auto write_elem = [](const auto& val, bool needs_space) {
            write(val);
            if (needs_space) pc(' ');
        };
        (write_elem(std::get<Is>(t), Is < size - 1), ...);
    }

    template<typename... Args>
    inline void write(const std::tuple<Args...> &t) {
        write_tuple_impl(t, std::index_sequence_for<Args...>{});
    }

    #ifdef __SIZEOF_INT128__
    inline void read(__int128 &x) {
        x = 0; bool sign = false; char c = gc();
        while (!isdigit(c)) { if (c == '-') sign = true; c = gc(); }
        while (isdigit(c)) { x = x * 10 + (c ^ 48); c = gc(); }
        if (sign) x = -x;
    }
    inline void write(__int128 x) {
        if (x < 0) { pc('-'); x = -x; }
        static char st[40]; int top = 0;
        do { st[top++] = '0' + (x % 10); x /= 10; } while (x);
        while (top--) pc(st[top]);
    }
    #endif

    #define io_init() do { \
        setvbuf(stdin, nullptr, _IOFBF, IN_LEN); \
        setvbuf(stdout, nullptr, _IOFBF, OUT_LEN); \
    } while(0)
}

fastIO 使用方法

为了使用fastIO的高性能读写功能,请务必在main函数开始时调用初始化函数:

int main() {
    fastIO::io_init(); // 必须调用此函数进行初始化

    int a, b;
    fastIO::read(a, b); // 读取
    fastIO::write(a + b); // 写出
    fastIO::pc('\n'); // 换行
    fastIO::flush(); // 程序结束前必须刷新缓冲区

    return 0;
}

感谢收看,再见!