跳到正文

算法·理论

Jason331 的武功秘籍

Jason331约 23 分钟
原文
文章信息与版本

文章信息

发布
2026年1月22日
收录
2026年1月30日
更新
2026年9月4日
篇幅
约 23 分钟

版本

  1. v2当前
  2. v1
代码模板
C++
// Code By Jason331
#include <bits/stdc++.h>
#include <cassert>
#ifdef __unix__
#include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
// #define TOOT_TOOT
#ifdef TOOT_TOOT
#pragma GCC optimize(2,3,"-fdelete-null-pointer-checks,inline-functions-called-once,-funsafe-loop-optimizations,-fexpensive-optimizations,-foptimize-sibling-calls,-ftree-switch-conversion,-finline-small-functions,inline-small-functions,-frerun-cse-after-loop,-fhoist-adjacent-loads,-findirect-inlining,-freorder-functions,no-stack-protector,-fpartial-inlining,-fsched-interblock,-fcse-follow-jumps,-fcse-skip-blocks,-falign-functions,-fstrict-overflow,-fstrict-aliasing,-fschedule-insns2,-ftree-tail-merge,inline-functions,-fschedule-insns,-freorder-blocks,-fwhole-program,-funroll-loops,-fthread-jumps,-fcrossjumping,-fcaller-saves,-fdevirtualize,-falign-labels,-falign-loops,-falign-jumps,unroll-loops,-fsched-spec,-ffast-math,-fpeephole2,-ftree-vrp,-ftree-pre,-fipa-sra,-fgcse-lm,-fgcse,inline,Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#endif
using namespace std;
#define heap priority_queue
#define uset unordered_set
#define umap unordered_map
#define mpr make_pair
// #include <bits/extc++.h>
// #define map gp_hash_table
// using namespace __gnu_cxx;
// using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned int u32;
typedef unsigned long long ull;
typedef long double lf;
typedef __int128_t i128;
typedef __float128 llf;
#define CONST __attribute__((const))
#define PURE __attribute__((pure))
#define PACKED __attribute__((packed))
#define START __attribute__((constructor))
#define END __attribute__((destructor))
#define told __builtin_expect
#define range(i,start,end) for(auto i = (start);i <= (end);i++)
#define rrange(i,start,end) for(auto i = (start);i >= (end);i--)
#define rep(i,start,end) for(auto i = (start);i < (end);i++)
#define rrep(i,start,end) for(auto i = (start);i > (end);i--)
#define print_list(name,start,end) \
    printf("%s[%d-%d]: ",#name,start,end);\
    range(i,start,end) printf("%d ",name[i]);\
    printf("\n");

#ifdef ONLINE_JUDGE
#define DEBUG 0
#define READ_FROM_FILE 1
#else
#define DEBUG 0
#define READ_FROM_FILE 1
#endif

mt19937 rng(15);

namespace FastIO
{
    #if DEBUG
    // nothing
    #else
    constexpr int __ISIZ = 1 << 16,__OSIZ = 1 << 16;// buf size
    char __ibuf[__ISIZ],__obuf[__OSIZ];// buf
    char *__ip1 = __ibuf,*__ip2 = __ibuf,*__op1 = __obuf;
    char *const __op2 = __obuf + __OSIZ;
    #ifdef __unix__
    #ifdef READ_FROM_FILE
    struct stat __state;
    uint8_t *__ip;

    int __mmap_init = []{
        fstat(0,&__state);
        __ip = (uint8_t*)mmap(NULL,__state.st_size,PROT_READ,MAP_PRIVATE,0,0);
        return 0;
    } ();
    #else
    #define buf_read(buf,size) read(0,buf,size)
    #endif
    #define buf_write(buf,size) write(1,buf,size)
    #else
    #define buf_read(buf,size) fread(buf,1,size,stdin)
    #define buf_write(buf,size) fwrite(buf,1,size,stdout)
    #endif
    inline END void flush() 
    {
        buf_write(__obuf,__op1 - __obuf);
        __op1 = __obuf;
    }
    #endif

    inline char getc()
    {
        #if DEBUG
        return getchar();
        #else
        #if defined(__unix__) && READ_FROM_FILE
        return *__ip++;
        #else
        if(told(__ip1 == __ip2,false))
            __ip2 = (__ip1 = __ibuf) + buf_read(__ibuf,__ISIZ);
        return __ip1 == __ip2?-1:*__ip1++;
        #endif
        #endif
    }

    inline void putc(char c)
    {
        #if DEBUG
        putchar(c);
        #else
        *__op1++ = c;
        if(told(__op1 == __op2,false)) 
            flush();
        #endif
    }

    inline void write(char c) {putc(c);}

    inline void write(const char *s)
    {
        for(const char *p = s;*p;p++)
            putc(*p);
    }

    inline void read(char &c) {c = getc();}
    inline void read(char *s)
    {
        char *p = s - 1;
        do *++p = getc();
        while(!isspace(*p));
        *p = '\0';
    }

    template <typename T>
    inline bool check_read(T &x)
    {
        bool f = false;
        char c;
        for(c = getc();!isdigit(c) && c != '-' && ~c;c = getc());
        if(c == '-')
        {
            f = true;
            c = getc();
        }
        if(told(c == -1,false)) 
            return false;
        for(x = 0;isdigit(c);c = getc())
            x = x * 10 + (c ^ '0');
        if(f) x = -x;
        return true;
    }

    template <typename T>
    inline void read(T &x)
    {
        bool f = false;
        char c;
        for(c = getc();!isdigit(c) && c != '-';c = getc());
        if(c == '-')
        {
            f = true;
            c = getc();
        }
        for(x = 0;isdigit(c);c = getc())
            x = x * 10 + (c ^ '0');
        if(f) x = -x;
    }

    template <typename T>
    inline void write(T x)
    {
        static constexpr int PSIZ = 40;
        static char sta[PSIZ];
        signed char top = 0;
        if(x < 0) x = -x,putc('-');
        do sta[top++] = x % 10 + '0';
        while(x /= 10);
        while(top--) putc(sta[top]);
    }

    template <typename T,typename... Ts>
    inline void read(T &x,Ts&... other)
    {
        read(x);
        read(other...);
    }

    template <typename T,typename... Ts>
    inline void write(T x,Ts... other)
    {
        write(x);
        write(other...);
    }

    template <typename... Ts>
    inline void writeln(Ts... x) {write(x...,'\n');}
    inline int readint() {int x;read(x);return x;}
    inline ll readll() {ll x;read(x);return x;}
}

using namespace FastIO;

signed main()
{
    
    return 0;
}
Fast IO(快速输入输出)

膜拜(目前)天下第一快读:link

本人常用的输入输出模板:

注意:此模板无法正确输出 INT_MIN 和 LONG_LONG_MIN,需要转换为范围更大的类型再输出,输入此类数时会产生有符号整型溢出的 UB,但是一般不会出锅。

C++
namespace
{
    constexpr int PSIZ = 40,ISIZ = 1 << 16,OSIZ = ISIZ;
    char ibuf[ISIZ],obuf[OSIZ],st[PSIZ];
    char *ip1 = ibuf,*ip2 = ibuf,*outp1 = obuf,*const outp2 = obuf + OSIZ,ltop;
    inline END void flush() {fwrite(obuf,1,outp1 - obuf,stdout);outp1 = obuf;}
    inline char getc() {if(ip1 == ip2) ip2 = (ip1 = ibuf) + fread(ibuf,1,ISIZ,stdin);return ip1 == ip2?-1:*ip1++;}
    inline void putc(char c) {*outp1++ = c;if(outp1 == outp2) flush();}
    template <typename T> inline void read(T &x) {bool flag = false;char c;for(c = getc();c < '0' && c != '-';c = getc());if(c == '-') flag = true,c = getc();for(x = 0;c >= '0';c = getc()) x = x * 10 + (c ^ '0');if(flag) x = -x;}
    template <typename T> inline void write(T x) {if(x < 0) putc('-'),x = -x;ltop = 0;do st[ltop++] = char(x % 10 ^ '0');while(x /= 10);while(ltop--) putc(st[ltop]);}
    template <typename T,typename... Ts> inline void read(T &x,Ts&... other) {read(x);read(other...);}
    template <typename T,typename... Ts> inline void write(char gap,T x,Ts... other) {write(x),putc(gap);write(other...);}
}
非压行版本
C++
namespace
{
    constexpr int PSIZ = 40,ISIZ = 1 << 16,OSIZ = ISIZ;
    char ibuf[ISIZ],obuf[OSIZ],st[PSIZ];
    char *ip1 = ibuf,*ip2 = ibuf,*outp1 = obuf,*const outp2 = obuf + OSIZ,ltop;

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

    inline char getc() 
    {
        if(ip1 == ip2)
            ip2 = (ip1 = ibuf) + fread(ibuf,1,ISIZ,stdin);
        return ip1 == ip2?-1:*ip1++;
    }

    inline void putc(char c) 
    {
        *outp1++ = c;
        if(outp1 == outp2) flush();
    }

    //WARNING: this function will make UB when input the min value of the variable
    //however, the result is correct most of the time
    template <typename T>
    inline void read(T &x) 
    {
        bool flag = false;
        char c;
        for(c = getc();c < '0' && c != '-';c = getc());
        if(c == '-') flag = true,c = getc();
        for(x = 0;c >= '0';c = getc())
            x = x * 10 + (c ^ '0');
    }

    //WARNING: this function cannot output the min value of the variable correctly
    //if you want to output an variable int x = INT_MIN
    //you should use "write((long long) x)"
    template <typename T>
    inline void write(T x) 
    {
        if(x < 0) putc('-'),x = -x;
        ltop = 0;
        do st[ltop++] = x % 10 + '0';
        while(x /= 10);
        while(ltop--) putc(st[ltop]);
    }

    template <typename T,typename... Ts>
    inline void read(T &x,Ts&... other)
    {
        read(x);
        read(other...);
    }

    template <typename T,typename... Ts>
    inline void write(char gap,T x,Ts... other)
    {
        write(x),putc(gap);
        write(other...);
    }
}
火车头

警告:洛谷无法使用,也不可以在赛场上使用。

C++
#pragma GCC optimize(2,3,"-fdelete-null-pointer-checks,inline-functions-called-once,-funsafe-loop-optimizations,-fexpensive-optimizations,-foptimize-sibling-calls,-ftree-switch-conversion,-finline-small-functions,inline-small-functions,-frerun-cse-after-loop,-fhoist-adjacent-loads,-findirect-inlining,-freorder-functions,no-stack-protector,-fpartial-inlining,-fsched-interblock,-fcse-follow-jumps,-fcse-skip-blocks,-falign-functions,-fstrict-overflow,-fstrict-aliasing,-fschedule-insns2,-ftree-tail-merge,inline-functions,-fschedule-insns,-freorder-blocks,-fwhole-program,-funroll-loops,-fthread-jumps,-fcrossjumping,-fcaller-saves,-fdevirtualize,-falign-labels,-falign-loops,-falign-jumps,unroll-loops,-fsched-spec,-ffast-math,-fpeephole2,-ftree-vrp,-ftree-pre,-fipa-sra,-fgcse-lm,-fgcse,inline,Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
快速除法 / 取模(Barrett 约减)
\gdef \go#1#2{\bigg \lfloor \frac {#1} {#2} \bigg \rfloor} \gdef \up#1#2{\bigg \lceil \frac {#1} {#2} \bigg \rceil} \gdef \gos#1#2{\big \lfloor \frac {#1} {#2} \big \rfloor} \gdef \dis{\displaystyle}

以下所说的除法中,指的是向下取整的除法,即 C++ 中整数与整数之间的除法。

Barrett 约减通过实现固定除数的除法来实现固定模数的取模。

算法思想

假设我们的除数是 xx,我们知道对于任意实数 k,dk,d,有 kx=k×dxd\dis \frac {k} {x} = \frac {k \times \frac {d} {x}} {d}

当我们选取 dd 为 22 的正整数次幂时,我们便可以通过位移来实现以 dd 为除数的除法。于是我们只需要预处理 dx\dis \frac {d} {x},就可以只用乘法和位移实现除法了。

误差分析

但是 C++ 中的除法向下取整,显然会有误差,我们需要选择合适的 dd 使得误差在可以接受的范围内。

在使用向下取整的除法时,dx\dis \frac {d} {x} 相对于 ⌊dx⌋\dis \go d x 的误差为 (−1,0](-1,0],将这个误差带入上面的式子可以得到: ⌊k×⌊dx⌋d⌋\dis \go {k \times \gos {d} {x}} {d} 相对于 ⌊kx⌋\dis \go {k}{x} 的误差为 [−⌈kd⌉,0]\dis \big [-\up {k} {d},0 \big ]。

那么在使用这个式子计算 r=k mod x=k−⌊kx⌋×x=r = \dis k \bmod x = k - \go {k} {x} \times x = 时,误差应该是 [0,⌈kd⌉×x]\dis [0,\up {k} {d} \times x],由取整可以知道,误差必定是 xx 的倍数。

一般实现时选取 d≥kd \ge k,这样就能保证取模结果最多误差 1×x1 \times x,只需要在计算完后判断结果 rr,如果 r≥xr \ge x,将 rr 赋值为 r−xr - x 即可。

实现

需要用到 __int128。

C++
#define PURE __attribute__((pure))
typedef __int128 i128;
constexpr int R = 75;
struct mode//Barrett
{
	i128 __R,mod;
	mode(){}
	mode(int _mod)
	{
		mod = _mod;
		__R = ((i128)1 << R) / _mod;
	}

	mode(const mode &a) 
	{
		__R = a.__R;
		mod = a.mod;
	}
	
	PURE friend const ll operator %(i128 x,mode xmod)
	{
		ll ans = x - (xmod.__R * x >> R) * xmod.mod;
		ans = ans - (xmod.__R * ans >> R) * xmod.mod;
		//会发现这里因为 __int128 太大了,可能误差不止一个 mod,所以需要做两次。
		return ans >= xmod.mod?ans - xmod.mod:ans;
	}
	
	template <typename T>
	PURE friend const ll operator %(T x,mode xmod)
	{
		int ans = x - (xmod.__R * x >> R) * xmod.mod;
		return ans >= xmod.mod?ans - xmod.mod:ans;
	}
};
属性(attribute)

C++ 中的属性(attribute)是可以让我们沟通编译器的神器。

很多属性并不会改变代码功能,但依旧起着很重要的作用。

以后再来填坑吧。

原文