模板

· · 算法·理论

常用网站

Graph Editor

OI Wiki #1 #2

OIerDb Ng #1 #2

CodingOIer's 洛谷工具站

犇圈 / Benben Circle

洛谷保存站

洛谷帖子保存站

Codeforces

Sphere Online Judge (SPOJ)

AtCoder

Online Judge

Virtual Judge

梦熊联盟

NOI大纲

NOI大纲(2023年修订版)

NOI大纲(2025年修订版)

Linux命令

类型 命令 作用
目录操作 pwd 显示当前工作目录的绝对路径
^ cd 切换目录
^ ls 列出目录内容
文件操作 mkdir 创建目录
^ cp 复制文件
^ mv 重名或移动文件
^ rm 递归删除目录
^ touch 创建空文件或更新文件时间戳‌
权限与进程管理 chmod 修改权限
^ kill 终止进程
系统信息查询 df 查看磁盘空间
^ du 统计目录大小‌

编译选项

-O2 -std=c++14 -static

缺省源

#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define i128 __int128
#define mp(a,b) make_pair(a,b)
using namespace std;

比赛相关

快读

inline int read()
{
    int s=1,a=0;
    char c=getchar();
    while(c!='-'&&(c<'0'||c>'9')) c=getchar();
    if(c=='-') s=-1,c=getchar();
    while(c>='0'&&c<='9') a=a*10+(c-'0'),c=getchar();
    return s*a;
}

快输

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

语言基础

运算符优先级

运算 - OI Wiki

级别 运算符 描述
1 :: 作用域解析符
2 ++ 后自增运算符
^ -- 后自减运算符
^ () 函数调用
^ [] 数组数据获取
^ . 对象型成员调用
^ -> 指针型成员调用
3 ++ 前自增运算符
^ -- 前自减运算符
^ + 正号
^ - 负号
^ ! 逻辑取反
^ ~ 按位取反
^ * 指针取值
^ & 值取指针
^ sizeof 返回类型内存
^ new 动态元素内存分配
^ delete 动态析构元素内存
5 * 乘法
^ / 除法
^ % 取余数(模运算)
6 + 加法
^ - 减法
7 << 位左移
^ >> 位右移
9 < 小于
^ <= 小于等于
^ > 大于
^ >= 大于等于
10 == 等于
^ != 不等于
11 & 位与运算
12 ^ 位异或运算
13 \| 位或运算
14 && 逻辑与运算
15 \|\| 逻辑或运算
16 ? : 条件运算符
^ = 赋值
^ += 加赋值运算
^ -= 减赋值运算
17 , 逗号分隔符

运算符重载

重载运算符 - OI Wiki

struct node
{
    ll d;
    bool operator < (const node &u) const {return d<u.d;}
};

算法基础

时间复杂度

复杂度简介 - OI Wiki

O(1)<O(\alpha(n))<O(\log\log n)<O(\log n)<O(\sqrt{n})<O(n)<O(n\log\log n)<O(n\log n)<O(n^2)<O(n^2\log n)<O(n^3)<O(n^k)(k>3)<O(2^{\sqrt{n}})<O(2^n)<O(n\cdot2^n)<O(e^n)<O(n!)<O(n^n)<O(2^{2^n})

归并排序/求逆序对

归并排序 - OI Wiki

P1908 逆序对

ll n,a[MAXN],p[MAXN];
ll gb(ll L,ll R)
{
    if(L==R)
        return 0;
    ll mid=(L+R)/2,sum;
    sum=gb(L,mid)+gb(mid+1,R);
    for(ll i=L;i<=R;i++)
        p[i]=a[i];
    ll i=L,j=mid+1,k=L;
    while(i<=mid||j<=R)
    {
        if(i>mid)
        {
            a[k++]=p[j++];
            sum+=mid-i+1;
        }
        else if(j>R)
            a[k++]=p[i++];
        else if(p[i]<=p[j])
            a[k++]=p[i++];
        else if(p[i]>p[j])
        {
            a[k++]=p[j++];
            sum+=mid-i+1;
        }
    }
    return sum;
}

搜索

A*算法

A* - OI Wiki

令 g(u)\in[0,d(u,t)] 为 u 到 t 的距离的估计函数,则 s\rightarrow u\rightarrow t 的估计路径长度 f(u)=d(s,u)+g(u),并以 f(u) 为关键字插入优先队列。

迭代加深搜索 (DDFS)

迭代加深搜索 - OI Wiki

每次限制搜索深度且深度逐渐递增的深度优先搜索。

IDA*算法

IDA* - OI Wiki

以路径估计函数 f(u) 为关键字判断是否超过 DDFS 阈值。

动态规划

LIS 最长上升子序列

动态规划基础 - OI Wiki

ll LIS[MAXN],L=0;
for(ll i=1;i<=n;i++)
    if(!L||LIS[L]<a[i]) LIS[++L]=a[i];
    else LIS[lower_bound(LIS+1,LIS+L+1,a[i])-LIS]=a[i];

LCS 最长公共子序列

动态规划基础 - OI Wiki

P1439 【模板】最长公共子序列

ll Map[MAXN],LIS[MAXN],L=0;
for(ll i=1;i<=n;i++) Map[a[i]]=i;
for(ll i=1;i<=n;i++)
    if(!L||LIS[L]<Map[b[i]]) LIS[++L]=Map[b[i]];
    else LIS[lower_bound(LIS+1,LIS+L+1,Map[b[i]])-LIS]=Map[b[i]];

多重背包

背包 DP - OI Wiki

dp[i][j]=\max_{k=0}^{k[i]}\{dp[i-1][j-k\times c[i]]+k\times w[i]\}

时间复杂度:O(V\sum k)

二进制优化

将 k[i] 个物品按二进制拆分为若干个由原来 2^p 个物品组合而成的物品。

时间复杂度:O(V\sum\log_2k)

单调队列优化

单调队列/单调栈优化 - OI Wiki

原式:dp[i][j]=\max_{k=0}^{k[i]}\{dp[i-1][j-k\times c[i]]+k\times w[i]\}

令 a=\left\lfloor\cfrac{j}{c[i]}\right\rfloor,b=j-a\times c[i]

则有 j=a\times c[i]+b

dp[i][b+a\times c[i]] & = & \max_{k=0}^{k[i]}\{dp[i-1][b+a\times c[i]-k\times c[i]]+k\times w[i]\} \\ & = & \max_{k=0}^{k[i]}\{dp[i-1][b+(a-k)\times c[i]]+k\times w[i]\} \end{array}

令 t=a-k:

dp[i][b+a\times c[i]] & = & \max_{t=a-k[i]}^a\{dp[i-1][b+t\times c[i]]+(a-t)\times w[i]\} \\ & = & \max_{t=a-k[i]}^a\{dp[i-1][b+t\times c[i]]-t\times w[i]\}+a\times w[i] \end{array}

综上:dp[i][b+a\times c[i]]=\max_{t=a-k[i]}^a\{dp[i-1][b+t\times c[i]]-t\times w[i]\}+a\times w[i]

1\le i\le n,0\le b<c[i],k[i]\le a\le \left\lfloor\cfrac{V-b}{c[i]}\right\rfloor

时间复杂度:O(nV)

ll n,m,c[MAXN],w[MAXN],k[MAXN],num[MAXN],dp[MAXN][MAXM];
ll val(ll i,ll b,ll t)
{
    return dp[i-1][b+t*c[i]]-t*w[i];
}
void calc()
{
    for(ll i=1;i<=n;i++)
        for(ll b=0;b<c[i];b++)
        {
            deque<ll> q;
            for(ll a=k[i];a<=(m-b)/c[i];a++)
            {
                if(q.size()&&q.front()<a-num[i]) q.pop_front();
                while(q.size()&&val(i,b,q.back())<val(i,b,a)) q.pop_back();
                q.push_back(a);
                dp[i][b+a*c[i]]=val(i,b,q.front())+a*w[i];
            }
        }
}

区间 dp

区间 DP - OI Wiki

P1775 石子合并(弱化版)

dp[i][j]=\begin{cases}0 & i=j \\ +\infty & i\ne j\end{cases}
for(ll len=1;len<=N;len++)
    for(ll l=1;l+len-1<=N;l++)
    {
        ll r=l+len-1;
        for(ll k=l;k<r;k++)
            dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]+f[l][r]);
    }

四边形不等式优化

四边形不等式优化 - OI Wiki

P1880 [NOI1995] 石子合并

适用于区间 dp 方程:dp[i][j]=\min(dp[i][k]+dp[k][j])+f[i][j]

条件:\forall a<b\le c<d,f[a][c]+f[b][d]\le f[a][d]+f[b][c]

定理:

  1. 若 f[i][j] 满足四边形不等式,则 dp[i][j] 满足四边形不等式。
  2. 若 dp[i][j] 满足四边形不等式,则 dp[i][j] 取得最优值时对应的下标 s[i][j] 单调,即 s[i][j-1]\le s[i][j]\le s[i+1][j]。

初始化:s[i][i]=i

for(ll len=1;len<=N;len++)
    for(ll l=1;l+len-1<=N;l++)
    {
        ll r=l+len-1;
        for(ll k=s[l][r-1];k<=s[l+1][r];k++)
            if(dp[l][k]+dp[k+1][r]+f[l][r]<dp[l][r])
            {
                dp[l][r]=dp[l][k]+dp[k+1][r]+f[l][r];
                s[l][r]=k;
            }
    }

字符串

字符串哈希

字符串哈希 - OI Wiki

将字符串 s 第 l 至 r 位的子串表示为 s[l,r],令 s[l,r] 的哈希值 f(s[l,r]) 以 b 为进制,则二者满足如下关系:

f(s[l,r])=\underset{k=l}{\overset{r}{\sum}}s[k]\cdot b^{r-k}=s[l]\cdot b^{r-l}+s[l+1]\cdot b^{r-l-1}+\cdots+s[r-1]\cdot b+s[r]
  1. f(s+t)=f(s)\cdot b^{|t|}+f(t)
  2. 令 s 的前缀所对哈希值 f_i(s)=f(s[1,i]),则有:

    f_i(s)=f_{i-1}(s)\cdot b+s[i] f(s[l,r])=f_r(s)-f_{l-1}(s)\cdot b^{r-l+1}
class HASH
{
    private:
        struct node
        {
            string s;
            ll hash,p;
            node(){}
            node(string s,ll hash,ll p):s(s),hash(hash),p(p){}
        }data;
        ll pre[MAXN];
    public:
        HASH(){}
        HASH(string s,ll p)
        {
            data.s=s,data.p=p;
            pre[0]=0;
            for(ll i=1;i<=s.size();i++)
                pre[i]=(pre[i-1]*128+s[i-1])%p;
            data.hash=pre[s.size()];
        }
        static ll Pow(ll a,ll x,ll p)
        {
            a%=p;
            ll s=1;
            while(x)
            {
                if(x%2) s=s*a%p;
                x/=2;
                a=a*a%p;
            }
            return s;
        }
        node getHash(ll l,ll r)
        {
            return node(data.s.substr(l-1,r-l+1),
                        (pre[r]-pre[l-1]*Pow(128,r-l+1,data.p)%data.p+data.p)%data.p,
                        data.p);
        }
        static node addHash(node x,node y)
        {
            return node(x.s+y.s,
                        (x.hash*Pow(128,y.s.size(),x.p)%x.p+y.hash)%x.p,
                        x.p);
        }
};
class HASH
{
    private:
        struct node
        {
            string s;
            ll hash,p;
            node(){}
            node(string s,ll hash,ll p):s(s),hash(hash),p(p){}
        }data;
        ll pre[MAXN];
    public:
        HASH(){}
        HASH(string s,ll p)
        {
            data.s=s,data.p=p;
            pre[0]=0;
            for(ll i=1;i<=s.size();i++)
                pre[i]=(pre[i-1]*128+s[i-1])%p;
            data.hash=pre[s.size()];
        }
        static ll Pow(ll a,ll x,ll p)
        {
            a%=p;
            ll s=1;
            while(x)
            {
                if(x%2) s=s*a%p;
                x/=2;
                a=a*a%p;
            }
            return s;
        }
        ll getHash(ll l,ll r)
        {
            return (pre[r]-pre[l-1]*Pow(128,r-l+1,data.p)%data.p+data.p)%data.p;
        }
};

字典树

字典树 (Trie) - OI Wiki

ll Tree[MAXN][70],L,cnt[MAXN];
char S[MAXN];
ll getNum(char c)
{
    if(c>='A'&&c<='Z') return c-'A';
    else if(c>='a'&&c<='z') return c-'a'+26;
    else if(c>='0'&&c<='9') return c-'0'+52;
    return -1;
}
void build()
{
    ll n=strlen(S+1),d=0;
    for(ll i=1;i<=n;i++)
    {
        if(Tree[d][getNum(S[i])])
            d=Tree[d][getNum(S[i])];
        else
        {
            L++;
            Tree[d][getNum(S[i])]=L;
            d=L;
        }
        cnt[d]++;
    }
}
ll search()
{
    ll n=strlen(S+1),d=0;
    for(ll i=1;i<=n;i++)
        if(Tree[d][getNum(S[i])])
            d=Tree[d][getNum(S[i])];
        else return 0;
    return cnt[d];
}

KMP

前缀函数与 KMP 算法 - OI Wiki

ll kmp[MAXN];
string pat,txt;
void build()
{
    ll j=-1;
    kmp[0]=-1;
    for(ll i=1;i<pat.size();i++)
    {
        while(j!=-1&&pat[j+1]!=pat[i]) j=kmp[j];
        if(pat[j+1]==pat[i]) j++;
        kmp[i]=j;
    }
}
void work()
{
    ll j=-1;
    for(ll i=0;i<txt.size();i++)
    {
        while(j!=-1&&pat[j+1]!=txt[i]) j=kmp[j];
        if(pat[j+1]==txt[i]) j++;
        if(j==pat.size()-1)
        {

        }
    }
}
for(ll i=2,j=0;i<=n;i++)
{
    while(j&&S[j+1]!=S[i]) j=kmp[j];
    if(S[j+1]==S[i]) j++;
    kmp[i]=j;
}

AC自动机

AC 自动机 - OI Wiki

P3808 AC 自动机(简单版)

P3796 AC 自动机(简单版 II)

字典树构建

void buildTrie(ll t)
{
    ll len=strlen(s[t]+1);
    ll d=0;
    for(ll i=1;i<=len;i++)
        if(nxt[d][s[t][i]-'a']) d=nxt[d][s[t][i]-'a'];
        else L++,nxt[d][s[t][i]-'a']=L,d=L;
    id[d]=t;
}

fail 指针构建

void buildAC()
{
    queue<ll> q;
    for(ll i=0;i<26;i++)
        if(nxt[0][i]) q.push(nxt[0][i]);
    while(q.size())
    {
        ll t=q.front();
        q.pop();
        for(ll i=0;i<26;i++)
            if(nxt[t][i])
            {
                fail[nxt[t][i]]=nxt[fail[t]][i];
                q.push(nxt[t][i]);
            }
            else nxt[t][i]=nxt[fail[t]][i];
    }
}

匹配函数

void queryAC()
{
    ll len=strlen(t+1),d=0,sum=0;
    for(ll i=1;i<=len;i++)
    {
        d=nxt[d][t[i]-'a'];
        for(ll j=d;j;j=fail[j]) cnt[id[j]]++;
    }
}

拓扑排序优化

P5357 【模板】AC 自动机

void buildTrie(ll t)
{
    ll len=strlen(s+1);
    ll d=0;
    for(ll i=1;i<=len;i++)
        if(nxt[d][s[i]-'a']) d=nxt[d][s[i]-'a'];
        else L++,nxt[d][s[i]-'a']=L,d=L;
    if(!id[d]) id[d]=t;
    Map[t]=id[d];
}
void buildAC()
{
    queue<ll> q;
    for(ll i=0;i<26;i++)
        if(nxt[0][i]) q.push(nxt[0][i]);
    while(q.size())
    {
        ll t=q.front();
        q.pop();
        for(ll i=0;i<26;i++)
            if(nxt[t][i])
            {
                fail[nxt[t][i]]=nxt[fail[t]][i];
                q.push(nxt[t][i]);
            }
            else nxt[t][i]=nxt[fail[t]][i];
    }
}
void queryAC()
{
    ll len=strlen(t+1),d=0,sum=0;
    for(ll i=1;i<=len;i++)
    {
        d=nxt[d][t[i]-'a'];
        tag[d]++;
    }
}
void topo()
{
    queue<ll> q;
    for(ll i=1;i<=L;i++) In[fail[i]]++;
    for(ll i=1;i<=L;i++)
        if(!In[i]) q.push(i);
    while(q.size())
    {
        ll t=q.front();
        q.pop();
        if(!t) continue;
        cnt[id[t]]+=tag[t];
        tag[fail[t]]+=tag[t];
        In[fail[t]]--;
        if(!In[fail[t]]) q.push(fail[t]);
    }
}

Manacher

Manacher - OI Wiki

P3805 【模板】manacher

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll MAXN=1.1e7+5;
ll n,m,p[2*MAXN],ans;
char s[MAXN],c[2*MAXN];
void work()
{
    ll mid=1,r=1;
    for(ll i=2;i<=m;i++)
    {
        if(r>=i) p[i]=min(p[2*mid-i],(2*mid-i)-(mid-p[mid]));
        while(c[i-p[i]-1]==c[i+p[i]+1]) p[i]++;
        if(i+p[i]>r) r=i+p[i],mid=i;
    }
}
int main()
{
    scanf("%s",s+1);
    n=strlen(s+1);
    c[0]='?';
    for(ll i=1;i<=n;i++)
    {
        c[2*i-1]='#';
        c[2*i]=s[i];
    }
    c[2*n+1]='#';
    c[2*n+2]='!';
    m=2*n+1;
    work();
    for(ll i=1;i<=m;i++) ans=max(ans,p[i]);
    printf("%lld",ans);
    return 0;
}

数学

高精度加法/乘法

高精度计算 - OI Wiki

struct BigInt
{
    int num[1800],len;
    BigInt():len(0),num(){}
    BigInt(int x):len(0),num()
    {
        while(x)
        {
            num[++len]=x%10;
            x/=10;
        }
    }
    void read()
    {
        len=0;
        memset(num,0,sizeof(num));
        char c=getchar();
        while(c<'0'||c>'9') c=getchar();
        while(c>='0'&&c<='9')
        {
            num[++len]=c-'0';
            c=getchar();
        }
    }
    void write() const
    {
        for(int i=len;i>=1;i--)
            printf("%d",num[i]);
    }
    template<class T>
    BigInt operator + (const T &u) const
    {
        BigInt s;
        s.len=len;
        int x=u;
        for(int i=1;i<=s.len;i++)
        {
            s.num[i]=num[i]+x;
            x=s.num[i]/10;
            s.num[i]%=10;
        }
        while(x) s.num[++s.len]=x;
        return s;
    }
    BigInt operator + (const BigInt &u) const
    {
        BigInt s;
        s.len=max(len,u.len);
        int x=0;
        for(int i=1;i<=s.len;i++)
        {
            s.num[i]=num[i]+u.num[i]+x;
            x=s.num[i]/10;
            s.num[i]%=10;
        }
        if(x) s.num[++s.len]=x;
        return s;
    }
    template<class T>
    BigInt operator * (const T &u) const
    {
        BigInt s;
        s.len=len;
        int x=0;
        for(int i=1;i<=s.len;i++)
        {
            s.num[i]=num[i]*u+x;
            x=s.num[i]/10;
            s.num[i]%=10;
        }
        if(x) s.num[++s.len]=x%10;
        return s;
    }
    BigInt operator * (const BigInt &u) const
    {
        BigInt s;
        for(int i=1;i<=len;i++)
        {
            BigInt t;
            t.len=u.len+i-1;
            int x=0;
            for(int j=1;j<=u.len;j++)
            {
                t.num[j+i-1]=num[i]*u.num[j]+x;
                x=t.num[j+i-1]/10;
                t.num[j+i-1]%=10;
            }
            if(x) t.num[++t.len]=x%10;
            s=s+t;
        }
        return s;
    }
    bool operator < (const BigInt &u) const
    {
        if(len!=u.len) return len<u.len;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return num[i]<u.num[i];
        return false;
    }
    bool operator <= (const BigInt &u) const
    {
        if(len!=u.len) return len<u.len;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return num[i]<u.num[i];
        return true;
    }
    bool operator > (const BigInt &u) const
    {
        if(len!=u.len) return len>u.len;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return num[i]>u.num[i];
        return false;
    }
    bool operator >= (const BigInt &u) const
    {
        if(len!=u.len) return len>u.len;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return num[i]>u.num[i];
        return true;
    }
    bool operator == (const BigInt &u) const
    {
        if(len!=u.len) return false;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return false;
        return true;
    }
    bool operator != (const BigInt &u) const
    {
        if(len!=u.len) return true;
        for(int i=len;i>=1;i--)
            if(num[i]!=u.num[i]) return true;
        return false;
    } 
};

快速幂

快速幂 - OI Wiki

ll Pow(ll a,ll x,ll p)
{
    ll s=1;
    while(x)
    {
        if(x%2) s=s*a%p;
        x/=2;
        a=a*a%p;
    }
    return s;
}

欧拉函数

欧拉函数 - OI Wiki

递推法

若 n=\overset{k}{\underset{i=1}{\prod}}{p_i}^{c_i},其中 p_i 为 n 的所有质因数,则有 \varphi(n)=n\overset{k}{\underset{i=1}{\prod}}\left(1-\dfrac{1}{p_i}\right)

线性法

bool isPrime[MAXN];
ll prime[MAXN],euler[MAXN],cnt;
void Euler(ll n)
{
    memset(isPrime,1,sizeof(isPrime));
    isPrime[1]=0,euler[1]=1;
    for(ll i=2;i<=n;i++)
    {
        if(isPrime[i])
        {
            prime[++cnt]=i;
            euler[i]=i-1;
        }
        for(ll j=1;j<=cnt&&i*prime[j]<=n;j++) 
        {
            isPrime[i*prime[j]]=0;
            if(i%prime[j]==0)
            {
                euler[i*prime[j]]=euler[i]*prime[j];
                break;
            }
            else euler[i*prime[j]]=euler[i]*euler[prime[j]];
        }
    }
}

欧拉筛

筛法 - OI Wiki

P3383 【模板】线性筛素数

bool isPrime[MAXN];
ll Prime[MAXN],cnt;
void GetPrime(ll n)
{
    memset(isPrime,1,sizeof(isPrime));
    isPrime[1]=0;
    for(ll i=2;i<=n;i++)
    {
        if(isPrime[i]) Prime[++cnt]=i;
        for(ll j=1;j<=cnt&&i*Prime[j]<=n;j++) 
        {
            isPrime[i*Prime[j]]=0;
            if(i%Prime[j]==0) break;
        }
    }
}
ll v[MAXN],prime[MAXN],cnt;
void GetPrime(ll n)
{
    for(ll i=2;i<=n;i++)
    {
        if(v[i]==0)
        {
            v[i]=i;
            prime[++cnt]=i;
        }
        for(ll j=1;j<=cnt&&i*prime[j]<=n;j++)
        {
            if(prime[j]>v[i]||prime[j]>n/i) break;
            v[i*prime[j]]=prime[j];
        }
    }
}

逆元

模逆元 - OI Wiki

单个逆元的求法: a^{-1}\equiv a^{p-2}\pmod{p}

多个逆元的求法:

\begin{cases} 1, & i=0 \\ a_iS_{i-1}, & i\ge1 \end{cases}= \begin{cases} 1, & i=0 \\ \prod_{j=1}^{i}a_j, & i\ge1 \end{cases}

则有 S_i^{-1}=a_iS_{i+1}^{-1},a_i^{-1}=S_{i-1}S_i^{-1}

线性求逆元: i^{-1}\equiv-\left\lfloor\dfrac{p}{i}\right\rfloor(p\bmod i)^{-1}\pmod{p}

拓展欧几里得(Exgcd)

线性同余方程 - OI Wiki

P5656 【模板】二元一次不定方程 (exgcd)

由 \gcd(a,b)=\gcd(b,a\bmod b) 得:

ax+by=\gcd(a,b) \Rightarrow bx'+(a\bmod b)y'=\gcd(a,b) \Rightarrow bx'+\left(a-\left\lfloor\dfrac{a}{b}\right\rfloor\cdot b\right)y'=\gcd(a,b) \Rightarrow ay'+b\left(x'-\left\lfloor\dfrac{a}{b}\right\rfloor y'\right)=\gcd(a,b) \Rightarrow\begin{cases}x=y' \\ y=x'-\left\lfloor\dfrac{a}{b}\right\rfloor y'\end{cases}

裴蜀定理:若方程 ax+by=c\ (a,b,c\in N^{*}) 有整数解,则 \gcd(a,b)|c

void exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1,y=0;
        return;
    }
    exgcd(b,a%b,x,y);
    ll _x=x,_y=y;
    x=_y,y=_x-(a/b)*_y;
}
void exgcd(ll &x,ll &y,ll a,ll b)
{
    if(b==0)
    {
        x=1,y=0;
        return;
    }
    ll _x,_y;
    exgcd(_x,_y,b,a%b);
    x=_y;
    y=_x-a/b*_y;
}

Lucas 定理

卢卡斯定理 - OI Wiki

P3807 【模板】卢卡斯定理/Lucas 定理

C_n^m\equiv C_{\lfloor\frac{n}{p}\rfloor}^{\lfloor\frac{m}{p}\rfloor}\cdot C_{n\bmod p}^{m\bmod p}\pmod{p}

容斥原理

容斥原理 - OI Wiki

|A_1\cup A_2\cup\cdots\cup A_m|=\underset{1\le i\le m}{\sum}|A_i|-\underset{1\le i<j\le m}{\sum}|A_i\cap A_j|+\underset{1\le i<j<k\le m}{\sum}|A_i\cap A_j\cap A_k|-\cdots+(-1)^{m-1}|A_1\cap A_2\cap\cdots\cap A_m| \left|\overset{n}{\underset{i=1}{\bigcup}}A_i\right|=\overset{n}{\underset{k=1}{\sum}}(-1)^{k-1}\underset{1\le i_1<i_2<\cdots<i_k\le n}{\sum}|A_{i_1}\cap A_{i_2}\cap\cdots\cap A_{i_k}|

高斯消元

高斯消元 - OI Wiki

线性方程组求解

P3389 【模板】高斯消元法

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll MAXN=105;
const double eps=1e-7;
ll n;
double a[MAXN][MAXN],b[MAXN],x[MAXN];
int main()
{
    scanf("%lld",&n);
    for(ll i=1;i<=n;i++)
    {
        for(ll j=1;j<=n;j++)
            scanf("%lf",&a[i][j]);
        scanf("%lf",&b[i]);
    }
    for(ll i=1;i<=n;i++)
    {
        ll t=i;
        double Max=fabs(a[i][i]);
        for(ll j=i+1;j<=n;j++)
            if(fabs(a[j][i])>Max)
            {
                t=j;
                Max=fabs(a[j][i]);
            }
        if(Max<eps)
        {
            printf("No Solution");
            return 0;
        }
        swap(a[i],a[t]);
        swap(b[i],b[t]);
        for(ll j=i+1;j<=n;j++)
        {
            double mul=a[j][i]/a[i][i];
            for(ll k=i;k<=n;k++) a[j][k]-=a[i][k]*mul;
            b[j]-=b[i]*mul;
        }
    }
    for(ll i=n;i>=1;i--)
    {
        double sum=0;
        for(ll j=i+1;j<=n;j++)
            sum+=a[i][j]*x[j];
        x[i]=(b[i]-sum)/a[i][i];
    }
    for(ll i=1;i<=n;i++)
        printf("%lf\n",x[i]);
    return 0;
}

求逆矩阵

P4783 【模板】矩阵求逆

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll MAXN=105;
const double eps=1e-7;
ll n;
double f[MAXN][MAXN],g[MAXN][MAXN];
void print()
{
    for(ll i=1;i<=n;i++)
    {
        for(ll j=1;j<=n;j++) printf("%lf ",g[i][j]);
        printf("\n");
    }
}
int main()
{
    scanf("%lld",&n);
    for(ll i=1;i<=n;i++)
        for(ll j=1;j<=n;j++)
            scanf("%lf",&f[i][j]);
    for(ll i=1;i<=n;i++)
        g[i][i]=1;
//  矩阵->三角 
    for(ll i=1;i<=n;i++)
    {
        ll t=i;
        double Max=fabs(f[i][i]);
        for(ll j=i+1;j<=n;j++)
            if(fabs(f[j][i])>Max)
            {
                t=j;
                Max=fabs(f[j][i]);
            }
        if(Max<eps)
        {
            printf("No Solution");
            return 0;
        }
        swap(f[i],f[t]);
        swap(g[i],g[t]);
        for(ll j=i+1;j<=n;j++)
        {
            double mul=f[j][i]/f[i][i];
            for(ll k=1;k<=n;k++)
            {
                f[j][k]-=f[i][k]*mul;
                g[j][k]-=g[i][k]*mul;
            }
        }
    }
//  三角->对角线 
    for(ll i=n;i>=1;i--)
    {
        for(ll j=1;j<=n;j++)
            g[i][j]/=f[i][i];
        f[i][i]=1;
        for(ll j=1;j<i;j++)
        {
            double mul=f[j][i];
            for(ll k=1;k<=n;k++)
                g[j][k]-=g[i][k]*mul;
            f[j][i]=0;
        }
    }
    print();
    return 0;
}

卡特兰数

卡特兰数 - OI Wiki

C_n & = & \begin{cases} 1, & n=0 \\ \sum_{i=0}^{n-1}C_iC_{n-i-1}, & n\ge1 \end{cases} \\ & = & \cfrac{C_{2n}^n}{n+1}=\cfrac{(2n)!}{n!(n+1)!} \\ & = & C_{2n}^n-C_{2n}^{n+1} \\ & = & \begin{cases} 1, & n=0 \\ \cfrac{4n-2}{n+1}\ C_{n-1}, & n\ge1 \end{cases} \end{array}

数据结构

并查集

并查集 - OI Wiki

P3367 【模板】并查集

const ll MAXN=40005;
ll f[MAXN];
void Init(ll n)
{
    for(ll i=1;i<=n;i++)
        f[i]=i;
    return;
}
ll Find(ll x)
{
    if(f[x]==x) return x;
    f[x]=Find(f[x]);
    return f[x];
}
void Add(ll x,ll y)
{
    Find(x),Find(y);
    f[f[y]]=f[x];
    return;
}
ll Count(ll n)
{
    ll ans=0;
    bool B[MAXN]={};
    for(ll i=1;i<=n;i++)
        if(!B[Find(i)])
        {
            B[f[i]]=true;
            ans++;
        }
    return ans;
}

ST表(稀疏表)

ST 表 - OI Wiki

P3865 【模板】ST 表 && RMQ 问题

ll n,a[100005],ST[100005][70];
void build()
{
    for(ll i=1;i<=n;i++) ST[i][0]=a[i];
    for(ll j=1,k=2;k<=n;j++,k*=2)
        for(ll i=1;i+k-1<=n;i++)
            ST[i][j]=max(ST[i][j-1],ST[i+k/2][j-1]);
}
ll search(ll l,ll r)
{
    ll len=log2(r-l+1);
    return max(ST[l][len],ST[r-(1<<len)+1][len]);
}

树状数组

树状数组 - OI Wiki

P3374 【模板】树状数组 1

P3368 【模板】树状数组 2

ll n,c[32005];
ll lowbit(ll x)
{
    return x&(-x);
}
void add(ll i,ll x)
{
    for(;i<=n;i+=lowbit(i))
        c[i]+=x;
}
ll search(ll i)
{
    ll sum=0;
    for(;i>0;i-=lowbit(i))
        sum+=c[i];
    return sum;
}

线段树

线段树基础 - OI Wiki

P3372 【模板】线段树 1

P3373 【模板】线段树 2

const ll MAXN=100005;
ll a[MAXN];
struct node
{
    ll L,R,sum,tag=0;
}Tree[4*MAXN];
void pushup(ll d)
{
    Tree[d].sum=Tree[d*2].sum+Tree[d*2+1].sum;
}
void build(ll d,ll L,ll R)
{
    Tree[d].L=L,Tree[d].R=R;
    if(L==R)
    {
        Tree[d].sum=a[L];
        return;
    }
    ll mid=(L+R)/2;
    build(d*2,L,mid);
    build(d*2+1,mid+1,R);
    pushup(d);
    return;
}
void lazy(ll d,ll k)
{
    Tree[d].sum+=(Tree[d].R-Tree[d].L+1)*k;
    Tree[d].tag+=k;
}
void pushdown(ll d)
{
    lazy(2*d,Tree[d].tag);
    lazy(2*d+1,Tree[d].tag);
    Tree[d].tag=0;
}
void update(ll d,ll x,ll y,ll k)
{
    if(Tree[d].L>=x&&Tree[d].R<=y)
    {
        lazy(d,k);
        return;
    }
    if(Tree[d].tag) pushdown(d);
    ll mid=(Tree[d].L+Tree[d].R)/2;
    if(x<=mid) update(d*2,x,y,k);
    if(y>mid) update(d*2+1,x,y,k);
    pushup(d);
    return;
}
ll search(ll d,ll x,ll y)
{
    if(Tree[d].L>=x&&Tree[d].R<=y) return Tree[d].sum;
    if(Tree[d].tag) pushdown(d);
    ll mid=(Tree[d].L+Tree[d].R)/2,ans=0;
    if(x<=mid) ans+=search(d*2,x,y);
    if(y>mid) ans+=search(d*2+1,x,y);
    return ans;
}

Treap 平衡树

二叉搜索树 & 平衡树 - OI Wiki

Treap - OI Wiki

P3369 【模板】普通平衡树

P6136 【模板】普通平衡树(数据加强版)

const ll INF=1e16;
ll root,tot;
struct node
{
    ll lc=0,rc=0,val,pri,sum,size;
}Tree[1100005];
ll New(ll val)
{
    tot++;
    Tree[tot].val=val;
    Tree[tot].pri=rand();
    Tree[tot].sum=1;
    Tree[tot].size=1;
    return tot;
}
void build()
{
    Tree[root].val=Tree[root].pri=-INF;
    Tree[root].sum=Tree[root].size=0;
}
void zig(ll &p) //右旋 
{
    ll q=Tree[p].lc;
    Tree[p].lc=Tree[q].rc;
    Tree[q].rc=p;
    p=q;
}
void zag(ll &p) //左旋 
{
    ll q=Tree[p].rc;
    Tree[p].rc=Tree[q].lc;
    Tree[q].lc=p;
    p=q;
}
void pushup(ll p)
{
    Tree[p].size=Tree[p].sum;
    if(Tree[p].lc) Tree[p].size+=Tree[Tree[p].lc].size;
    if(Tree[p].rc) Tree[p].size+=Tree[Tree[p].rc].size;
}
void Insert(ll &p,ll val)
{
    if(!p)
    {
        p=New(val);
        return;
    }
    if(val==Tree[p].val) Tree[p].sum++;
    else if(val<Tree[p].val)
    {
        Insert(Tree[p].lc,val);
        if(Tree[p].pri>Tree[Tree[p].lc].pri)
        {
            zig(p);
            pushup(Tree[p].rc);
        }
    }
    else if(val>Tree[p].val)
    {
        Insert(Tree[p].rc,val);
        if(Tree[p].pri>Tree[Tree[p].rc].pri)
        {
            zag(p);
            pushup(Tree[p].lc);
        }
    }
    pushup(p);
    return;
}
void Delete(ll &p,ll val)
{
    if(!p) return;
    if(val==Tree[p].val)
    {
        if(Tree[p].sum>1)
        {
            Tree[p].sum--;
            pushup(p);
            return;
        }
        if(Tree[p].lc&&Tree[p].rc)
        {
            if(Tree[Tree[p].lc].pri<Tree[Tree[p].rc].pri)
            {
                zig(p);
                Delete(Tree[p].rc,val);
            }
            else
            {
                zag(p);
                Delete(Tree[p].lc,val);
            }
            pushup(p);
        }
        else if(Tree[p].lc) p=Tree[p].lc;
        else if(Tree[p].rc) p=Tree[p].rc;
        else p=0;
        return;
    }
    else if(val<Tree[p].val) Delete(Tree[p].lc,val);
    else if(val>Tree[p].val) Delete(Tree[p].rc,val);
    pushup(p);
    return;
}
ll Search(ll p,ll val)
{
    if(!p) return 0;
    if(Tree[p].val<val) return Search(Tree[p].rc,val)+Tree[Tree[p].lc].size+Tree[p].sum;
    else return Search(Tree[p].lc,val);
}
ll Rank(ll p,ll k)
{
    if(!p) return 0;
    if(Tree[Tree[p].lc].size+1<=k&&Tree[Tree[p].lc].size+Tree[p].sum>=k) return Tree[p].val;
    else if(Tree[Tree[p].lc].size+Tree[p].sum<k) return Rank(Tree[p].rc,k-Tree[Tree[p].lc].size-Tree[p].sum);
    else if(Tree[Tree[p].lc].size+1>k) return Rank(Tree[p].lc,k);
}
ll SearchPre(ll p,ll val)
{
    if(!p) return -INF;
    if(Tree[p].val>=val) return SearchPre(Tree[p].lc,val);
    else return max(SearchPre(Tree[p].rc,val),Tree[p].val);
}
ll SearchSuff(ll p,ll val)
{
    if(!p) return INF;
    if(Tree[p].val<=val) return SearchSuff(Tree[p].rc,val);
    else return min(SearchSuff(Tree[p].lc,val),Tree[p].val);
}

笛卡尔树

笛卡尔树 - OI Wiki

P5854 【模板】笛卡尔树

定义:节点 i 的权值为 p[i] 且 p[i] 互不相同,构建一棵树使得节点编号满足二叉搜索树且点的权值满足堆的性质。

构建方法:用栈维护右链 p[i] 单调。

s.push(0);
for(ll i=1;i<=n;i++)
{
    ll last=0;
    while(p[s.top()]>p[i]) last=s.top(),s.pop();
    R[s.top()]=i;
    L[i]=last;
    s.push(i);
}

可持久化线段树

可持久化线段树 - OI Wiki

P3919 【模板】可持久化线段树 1(可持久化数组)

ll a[MAXN];
struct node
{
    ll data,Lson,Rson;
};
vector<node> Tree;
void build(ll d,ll L,ll R)
{
    if(L==R)
    {
        Tree[d].data=a[L];
        return;
    }
    ll mid=(L+R)/2;
    Tree[d].Lson=Tree.size();
    Tree.pb({0,0,0});
    build(Tree[d].Lson,L,mid);
    Tree[d].Rson=Tree.size();
    Tree.pb({0,0,0});
    build(Tree[d].Rson,mid+1,R);
}
void update(ll d1,ll d2,ll L,ll R,ll p,ll c)
{
    if(L==R)
    {
        Tree[d2].data=c;
        return;
    }
    ll mid=(L+R)/2;
    if(p<=mid)
    {
        Tree[d2].Rson=Tree[d1].Rson;
        Tree[d2].Lson=Tree.size();
        Tree.pb({0,0,0});
        update(Tree[d1].Lson,Tree[d2].Lson,L,mid,p,c);
    }
    else
    {
        Tree[d2].Lson=Tree[d1].Lson;
        Tree[d2].Rson=Tree.size();
        Tree.pb({0,0,0});
        update(Tree[d1].Rson,Tree[d2].Rson,mid+1,R,p,c);
    }
}
ll query(ll d,ll L,ll R,ll p)
{
    if(L==R) return Tree[d].data;
    ll mid=(L+R)/2;
    if(p<=mid) return query(Tree[d].Lson,L,mid,p);
    else return query(Tree[d].Rson,mid+1,R,p);
}

P3834 【模板】可持久化线段树 2

struct node
{
    ll Lson,Rson,sum;
};
vector<node> Tree;
void build(ll d,ll L,ll R)
{
    if(L==R) return;
    ll mid=(L+R)/2;
    Tree[d].Lson=Tree.size();
    Tree.pb({0,0,0});
    build(Tree[d].Lson,L,mid);
    Tree[d].Rson=Tree.size();
    Tree.pb({0,0,0});
    build(Tree[d].Rson,mid+1,R);
}
void update(ll d1,ll d2,ll L,ll R,ll p)
{
    if(L==R)
    {
        Tree[d2].sum=Tree[d1].sum+1;
        return;
    }
    ll mid=(L+R)/2;
    if(p<=mid)
    {
        Tree[d2].Rson=Tree[d1].Rson;
        Tree[d2].Lson=Tree.size();
        Tree.pb({0,0,0});
        update(Tree[d1].Lson,Tree[d2].Lson,L,mid,p);
    }
    else
    {
        Tree[d2].Lson=Tree[d1].Lson;
        Tree[d2].Rson=Tree.size();
        Tree.pb({0,0,0});
        update(Tree[d1].Rson,Tree[d2].Rson,mid+1,R,p);
    }
    Tree[d2].sum=Tree[Tree[d2].Lson].sum+Tree[Tree[d2].Rson].sum;
}
ll query(ll d1,ll d2,ll L,ll R,ll cnt,ll k)
{
    if(L==R) return L;
    ll mid=(L+R)/2;
    if(Tree[Tree[d2].Lson].sum-Tree[Tree[d1].Lson].sum+cnt>=k) return query(Tree[d1].Lson,Tree[d2].Lson,L,mid,cnt,k);
    else return query(Tree[d1].Rson,Tree[d2].Rson,mid+1,R,cnt+Tree[Tree[d2].Lson].sum-Tree[Tree[d1].Lson].sum,k);
}

哈夫曼编码

霍夫曼树 - OI Wiki

哈夫曼算法用于构造一棵哈夫曼树,算法步骤如下:

  1. 初始化:由给定的 n 个权值构造 n 棵只有一个根节点的二叉树,得到一个二叉树集合 F。
  2. 选取与合并:从二叉树集合 F 中选取根节点权值最小的两棵二叉树分别作为左右子树构造一棵新的二叉树,这棵新二叉树的根节点的权值为其左、右子树根结点的权值和。
  3. 删除与加入:从 F 中删除作为左、右子树的两棵二叉树,并将新建立的二叉树加入到 F 中。
  4. 重复 2、3 步,当集合中只剩下一棵二叉树时,这棵二叉树就是哈夫曼树。

哈夫曼树可用于构造最短的前缀编码,即哈夫曼编码(Huffman Code),其构造步骤如下:

  1. 设需要编码的字符集为:d_1,d_2,\dots,d_n,他们在字符串中出现的频率为:w_1,w_2,\dots,w_n。
  2. 以 d_1,d_2,\dots,d_n 作为叶结点,w_1,w_2,\dots,w_n 作为叶结点的权值,构造一棵哈夫曼树。
  3. 规定哈夫曼编码树的左分支代表 0,右分支代表 1,则从根结点到每个叶结点所经过的路径组成的 0、1 序列即为该叶结点对应字符的编码。

图论

树的直径

树的直径 - OI Wiki

P3304 [SDOI2013] 直径

定理:

求法1:树型dp

ll dfs(ll d,ll fa)
{
    ll fst=0,scd=0,Max=0;
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i]!=fa)
        {
            Max=max(Max,dfs(G[d][i],d));
            if(dp[G[d][i]]+1>=fst) scd=fst,fst=dp[G[d][i]]+1;
            else if(dp[G[d][i]]+1>=scd) scd=dp[G[d][i]]+1;
        }
    dp[d]=fst;
    return max(Max,fst+scd);
}

求法2:两遍dfs

void dfs(ll d,ll fa,ll l)
{
    if(l>L) s=d,L=l;
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i]!=fa) dfs(G[d][i],d,l+1);
}

LCA 最近公共祖先

最近公共祖先 - OI Wiki

P3379 【模板】最近公共祖先(LCA)

ll N,Dep[500005],Fa[500005][25];
vector<ll> G[500005];
void dfs(ll fa,ll d,ll dep)
{
    Dep[d]=dep;
    Fa[d][0]=fa;
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i]!=fa) dfs(d,G[d][i],dep+1);
    return;
}
void build()
{
    for(ll j=1;j<=20;j++)
        for(ll i=1;i<=N;i++)
            if(Fa[i][j-1]) Fa[i][j]=Fa[Fa[i][j-1]][j-1];
}
ll LCA(ll x,ll y)
{
    if(Dep[x]>Dep[y])
    {
        for(ll i=20;i>=0;i--)
            if(Fa[x][i]&&Dep[Fa[x][i]]>=Dep[y]) x=Fa[x][i];
    }
    else if(Dep[x]<Dep[y])
    {
        for(ll i=20;i>=0;i--)
            if(Fa[y][i]&&Dep[Fa[y][i]]>=Dep[x]) y=Fa[y][i];
    }
    if(x==y) return x;
    for(ll i=20;i>=0;i--)
        if(Fa[x][i]&&Fa[y][i]&&Fa[x][i]!=Fa[y][i]) x=Fa[x][i],y=Fa[y][i];
    return Fa[x][0];
}
ll N,Dep[500005],Fa[500005][25],Dis[500005][25];
struct node
{
    ll d,dis;
    node(){}
    node(ll d,ll dis):d(d),dis(dis){}
};
vector<node> G[500005];
void dfs(ll fa,ll d,ll dep)
{
    Dep[d]=dep;
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i].d!=fa)
        {
            Fa[G[d][i].d][0]=d;
            Dis[G[d][i].d][0]=G[d][i].dis;
            dfs(d,G[d][i].d,dep+1);
        }
    return;
}
void build()
{
    for(ll j=1;j<=20;j++)
        for(ll i=1;i<=N;i++)
            if(Fa[i][j-1])
            {
                Fa[i][j]=Fa[Fa[i][j-1]][j-1];
                Dis[i][j]=Dis[i][j-1]+Dis[Fa[i][j-1]][j-1];
            }
    return;
}
ll LCA(ll x,ll y)
{
    ll cnt=0;
    if(Dep[x]>Dep[y])
    {
        for(ll i=20;i>=0;i--)
            if(Fa[x][i]&&Dep[Fa[x][i]]>=Dep[y])
            {
                cnt+=Dis[x][i];
                x=Fa[x][i];
            }
    }
    else if(Dep[x]<Dep[y])
    {
        for(ll i=20;i>=0;i--)
            if(Fa[y][i]&&Dep[Fa[y][i]]>=Dep[x])
            {
                cnt+=Dis[y][i];
                y=Fa[y][i];
            }
    }
    if(x==y) return cnt;
    for(ll i=20;i>=0;i--)
        if(Fa[x][i]&&Fa[y][i]&&Fa[x][i]!=Fa[y][i])
        {
            cnt+=Dis[x][i]+Dis[y][i];
            x=Fa[x][i],y=Fa[y][i];
        }
    cnt+=Dis[x][0]+Dis[y][0];
    return cnt;
}

树链剖分

树链剖分 - OI Wiki

P3384 【模板】重链剖分/树链剖分

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const ll MAXN=1e5+5;
ll N,M,Rt,P,num[MAXN],op,x,y,z;
vector<ll> G[MAXN];

ll Dep[MAXN],Size[MAXN],son[MAXN],p[MAXN],val[MAXN],Fa[MAXN],Top[MAXN],cnt;
void dfs1(ll d,ll fa)
{
    ll Max=0;
    Size[d]=1;
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i]!=fa)
        {
            dfs1(G[d][i],d);
            Size[d]+=Size[G[d][i]];
            if(Size[G[d][i]]>Max)
            {
                Max=Size[G[d][i]];
                son[d]=G[d][i];
            }
        }
}
void dfs2(ll d,ll fa,ll dep,ll top)
{
    p[d]=++cnt;
    val[p[d]]=num[d];
    Dep[p[d]]=dep;
    Size[p[d]]=1;
    Top[p[d]]=p[top];
    if(!son[d]) return;
    dfs2(son[d],d,dep+1,top);
    Fa[p[son[d]]]=p[d];
    Size[p[d]]+=Size[p[son[d]]];
    for(ll i=0;i<G[d].size();i++)
        if(G[d][i]!=fa&&G[d][i]!=son[d])
        {
            dfs2(G[d][i],d,dep+1,G[d][i]);
            Fa[p[G[d][i]]]=p[d];
            Size[p[d]]+=Size[p[G[d][i]]];
        }
}

ll L[4*MAXN],R[4*MAXN],tag[4*MAXN],sum[4*MAXN];
void pushdown(ll d)
{
    tag[d*2]+=tag[d];
    tag[d*2+1]+=tag[d];
    sum[d*2]+=tag[d]*(R[d*2]-L[d*2]+1);
    sum[d*2+1]+=tag[d]*(R[d*2+1]-L[d*2+1]+1);
    tag[d]=0;
}
void pushup(ll d)
{
    sum[d]=sum[d*2]+sum[d*2+1];
}
void build(ll d,ll l,ll r)
{
    L[d]=l,R[d]=r;
    if(l==r)
    {
        sum[d]=val[l];
        return;
    }
    ll mid=(l+r)/2;
    build(d*2,l,mid);
    build(d*2+1,mid+1,r);
    pushup(d);
}
void query(ll d,ll l,ll r,ll t)
{
    if(l<=L[d]&&R[d]<=r)
    {
        tag[d]+=t;
        sum[d]+=(R[d]-L[d]+1)*t;
        return;
    }
    pushdown(d);
    ll mid=(L[d]+R[d])/2;
    if(l<=mid) query(d*2,l,r,t);
    if(mid<r) query(d*2+1,l,r,t);
    pushup(d);
}
ll search(ll d,ll l,ll r)
{
    if(l<=L[d]&&R[d]<=r) return sum[d];
    pushdown(d);
    ll mid=(L[d]+R[d])/2,s=0;
    if(l<=mid) s+=search(d*2,l,r);
    if(mid<r) s+=search(d*2+1,l,r);
    return s;
}

void queryChain(ll x,ll y,ll z)
{
    while(Top[x]!=Top[y])
    {
        if(Dep[Top[x]]<Dep[Top[y]]) swap(x,y);
        query(1,Top[x],x,z);
        x=Fa[Top[x]];
    }
    if(x>y) swap(x,y);
    query(1,x,y,z);
}
ll searchChain(ll x,ll y)
{
    ll s=0;
    while(Top[x]!=Top[y])
    {
        if(Dep[Top[x]]<Dep[Top[y]]) swap(x,y);
        s+=search(1,Top[x],x);
        x=Fa[Top[x]];
    }
    if(x>y) swap(x,y);
    return s+search(1,x,y);
}

int main()
{
    scanf("%lld%lld%lld%lld",&N,&M,&Rt,&P);
    for(ll i=1;i<=N;i++) scanf("%lld",&num[i]);
    for(ll i=1;i<N;i++)
    {
        scanf("%lld%lld",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
    dfs1(Rt,0);
    dfs2(Rt,0,1,Rt);
    build(1,1,N);
    for(ll i=1;i<=M;i++)
    {
        scanf("%lld",&op);
        if(op==1)
        {
            scanf("%lld%lld%lld",&x,&y,&z);
            queryChain(p[x],p[y],z);
        }
        else if(op==2)
        {
            scanf("%lld%lld",&x,&y);
            printf("%lld\n",searchChain(p[x],p[y])%P);
        }
        else if(op==3)
        {
            scanf("%lld%lld",&x,&z);
            query(1,p[x],p[x]+Size[p[x]]-1,z);
        }
        else if(op==4)
        {
            scanf("%lld",&x);
            printf("%lld\n",search(1,p[x],p[x]+Size[p[x]]-1)%P);
        }
    }
    return 0;
}

Floyd

最短路 - OI Wiki

B3647 【模板】Floyd

dis(i,j) & \exists dis(i,j) \\ +\infin & \nexists dis(i,j) \end{cases}
for(ll k=1;k<=n;k++)
    for(ll i=1;i<=n;i++)
        for(ll j=1;j<=n;j++)
            dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]);

SPFA

最短路 - OI Wiki

P3371 【模板】单源最短路径(弱化版)

ll dis[MAXN],times[MAXN];
vector<pair<ll,ll> > G[MAXN];
bool SPFA(ll s)
{
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    queue<ll> q;
    q.push(s);
    times[s]++;
    while(q.size())
    {
        ll t=q.front();
        q.pop();
        if(times[t]>n) return false;
        for(ll i=0;i<G[t].size();i++)
            if(dis[t]+G[t][i].second<dis[G[t][i].first])
            {
                dis[G[t][i].first]=dis[t]+G[t][i].second;
                q.push(G[t][i].first);
                times[G[t][i].first]++;
            }
    }
    return true;
}

差分约束系统

差分约束 - OI Wiki

P5960 【模板】差分约束

对于若干约束条件 x_i-x_j\le c_k,可将其变形为 x_i\le x_j+c_k。类比 dis[y]=dis[x]+w,可将其当作从节点 j 向节点 i 连一条长度为 c_k 的有向边。

增加一个 0 号点,从 0 号点向其它所有点连一条长度为 0 的边。以 0 为起点,用 SPFA 计算到其它所有点的最短路径。如果有负环,差分约束无解。

Dijkstra

最短路 - OI Wiki

P4779 【模板】单源最短路径(标准版)

二维

const ll INF=1e16;
struct node
{
    ll d,dis;
    node(){}
    node(ll _d,ll _dis){d=_d,dis=_dis;}
    bool operator < (const node &u) const {return dis > u.dis;}
};
ll dis[3005][3005];
vector<node> G[3005];
void Dijkstra(ll s)
{
    for(ll i=1;i<=n;i++) dis[i][s]=INF;
    bool b[3005]={};
    priority_queue<node> q;
    dis[s][s]=0;
    q.push(node(s,0));
    while(!q.empty())
    {
        ll t=q.top().d;
        q.pop();
        if(b[t]) continue;
        b[t]=true;
        for(ll i=0;i<G[t].size();i++)
        {
            if(b[G[t][i].d]) continue;
            if(dis[t][s]+G[t][i].dis<dis[G[t][i].d][s])
            {
                dis[G[t][i].d][s]=dis[t][s]+G[t][i].dis;
                q.push(node(G[t][i].d,dis[G[t][i].d][s]));
            }
        }
    }
}

一维

const ll INF=1e16;
struct node
{
    ll d,dis;
    node(){}
    node(ll _d,ll _dis){d=_d,dis=_dis;}
    bool operator < (const node &u) const {return dis > u.dis;}
};
ll dis[10005];
vector<node> G[10005];
void Dijkstra(ll s)
{
    for(ll i=1;i<=n;i++) dis[i]=INF;
    bool b[10005]={};
    priority_queue<node> q;
    dis[s]=0;
    q.push(node(s,0));
    while(!q.empty())
    {
        ll t=q.top().d;
        q.pop();
        if(b[t]) continue;
        b[t]=true;
        for(ll i=0;i<G[t].size();i++)
        {
            if(b[G[t][i].d]) continue;
            if(dis[t]+G[t][i].dis<dis[G[t][i].d])
            {
                dis[G[t][i].d]=dis[t]+G[t][i].dis;
                q.push(node(G[t][i].d,dis[G[t][i].d]));
            }
        }
    }
}

Tarjan

强连通分量

强连通分量 - OI Wiki

B3609 [图论与代数结构 701] 强连通分量

ll DFN[10005],Low[10005],L,ansL;
bool B[10005];
vector<ll> G[10005],ans[10005];
stack<ll> s;
ll Tarjan(ll d)
{
    s.push(d);
    B[d]=true;
    DFN[d]=++L;
    Low[d]=DFN[d];
    for(ll i=0;i<G[d].size();i++)
        if(!DFN[G[d][i]])
            Low[d]=min(Low[d],Tarjan(G[d][i]));
        else if(B[G[d][i]])
            Low[d]=min(Low[d],DFN[G[d][i]]);
    if(DFN[d]==Low[d])
    {
        ansL++;
        while(s.top()!=d)
        {
            ans[ansL].push_back(s.top());
            B[s.top()]=false;
            s.pop();
        }
        ans[ansL].push_back(s.top());
        B[s.top()]=false;
        s.pop();
    }
    return Low[d];
}
ll Tarjan(ll d)
{
    s.push(d);
    vis[d]=true;
    Low[d]=DFN[d]=++L;
    for(auto u:G[d])
        if(!DFN[u.p]) Low[d]=min(Low[d],Tarjan(u.p));
        else if(vis[u.p]) Low[d]=min(Low[d],DFN[u.p]);
    if(DFN[d]==Low[d])
    {
        P.pb(vector<ll>());
        while(s.top()!=d)
        {
            P.back().pb(s.top());
            vis[s.top()]=false;
            s.pop();
        }
        P.back().pb(s.top());
        vis[s.top()]=false;
        s.pop();
    }
    return Low[d];
}

点双连通分量

双连通分量 - OI Wiki

P8435 【模板】点双连通分量

ll DFN[500005],Low[500005],L,ansL;
vector<ll> G[500005],ans[500005];
stack<ll> s;
ll Tarjan(ll d,ll root)
{
    DFN[d]=Low[d]=++L;
    if(d==root&&G[d].size()==0)
    {
        ans[++ansL].push_back(d);
        return 0;
    }
    s.push(d);
    for(ll i=0;i<G[d].size();i++)
        if(!DFN[G[d][i]])
        {
            Low[d]=min(Low[d],Tarjan(G[d][i],root));
            if(DFN[d]<=Low[G[d][i]])
            {
                ansL++;
                while(s.top()!=G[d][i])
                {
                    ans[ansL].push_back(s.top());
                    s.pop();
                }
                ans[ansL].push_back(s.top());
                s.pop();
                ans[ansL].push_back(d);
            }
        }
        else Low[d]=min(Low[d],DFN[G[d][i]]);
    return Low[d];
}

割点

割点和桥 - OI Wiki

P3388 【模板】割点(割顶)

ll DFN[20005],Low[20005],L,ans[20005],ansL;
bool B[20005];
vector<ll> G[20005];
ll Tarjan(ll d,ll root)
{
    DFN[d]=Low[d]=++L;
    ll cnt=0;
    for(ll i=0;i<G[d].size();i++)
        if(!DFN[G[d][i]])
        {
            Low[d]=min(Low[d],Tarjan(G[d][i],root));
            cnt++;
            if(!B[d]&&(d==root&&cnt>1||d!=root&&DFN[d]<=Low[G[d][i]]))
            {
                ans[++ansL]=d;
                B[d]=true;
            }
        }
        else Low[d]=min(Low[d],DFN[G[d][i]]);
    return Low[d];
}

割边

割点和桥 - OI Wiki

P8436 【模板】边双连通分量

ll DFN[500005],Low[500005],L;
bool cut[2000005];
struct node
{
    ll d,num;
    bool cut;
    node(){}
    node(ll _d,ll _num){d=_d,num=_num;}
};
vector<node> G[500005];
ll Tarjan(ll fa,ll d)
{
    DFN[d]=Low[d]=++L;
    for(ll i=0;i<G[d].size();i++)
    {
        if(G[d][i].d==fa) continue;
        if(!DFN[G[d][i].d])
        {
            Low[d]=min(Low[d],Tarjan(d,G[d][i].d));
            if(DFN[d]<Low[G[d][i].d]) cut[G[d][i].num]=true;
        }
        else Low[d]=min(Low[d],DFN[G[d][i].d]);
    }
    return Low[d];
}

圆方树(点双连通分量缩点)

圆方树 - OI Wiki

设原图为 G,其中包含 k 个极大点双连通分量 \{C_k\}。

则另 V(G) 为圆点,创建 k 个方点 \{P_k\} 与 \{C_k\} 一一对应。

则新图为 G'(V(G)+P,\{P_k\longleftrightarrow V(C_k)\})。

2-SAT

2-SAT - OI Wiki

P4782 【模板】2-SAT

欧拉回路

欧拉图 - OI Wiki

P7771 【模板】欧拉路径

ll del[100005];
vector<ll> G[100005];
stack<ll> ans;
void dfs(ll d)
{
    for(ll i=del[d];i<G[d].size();i=del[d])
    {
        del[d]=i+1;
        dfs(G[d][i]);
    }
    ans.push(d);
}

网络流

基本概念

网络流简介 - OI Wiki

有向图:G=(V,E)。

源点:s。

汇点:t。

容量:c(u,v)。

流:f(u,v)\in[0,c(u,v)]。

净流量:f(u)=\sum_{x\in V}f(u,x)-\sum_{x\in V}f(x,u)。

流量:|f|=f(u)=-f(t)。

$\{S,T\}$ 的容量:$||S,T||=\sum_{u\in S}\sum_{v\in T}c(u,v)$。 ### 最大流最小割定理 对于任意网络 $G=(V,E)$,其上的最大流 $f$ 和最小割 $\{S,T\}$ 总是满足 $|f|=||S,T||$。 ### 最大流问题 [最大流 - OI Wiki](https://oi-wiki.org/graph/flow/max-flow/) #### Ford–Fulkerson 增广 [P3376 【模板】网络最大流](https://www.luogu.com.cn/problem/P3376) 对于每条边 $(u,v)$,我们都新建一条反向边 $(v,u)$ 且满足 $c(v,u)=0,f(u,v)=-f(v,u)$。 增广路:一条从 $s$ 到 $t$ 的路径(边集为 $E'$)且满足 $c_f=\min_{(u,v)\in E'}\{c(u,v)-f(u,v)\}>0$,则此时可将路径上每条边的流增加 $c_f$。 ##### Edmonds–Karp 算法 在 Ford–Fulkerson 增广的基础上,用 bfs 求解增广路。 时间复杂度:$O(|V||E|)$。 ```cpp #include<bits/stdc++.h> #define ll long long #define pb push_back using namespace std; const ll MAXN=1205; ll n,m,s,t,ans; struct node { ll u,v,cap,flow; }; vector<node> edge; vector<ll> G[MAXN]; void add(ll u,ll v,ll w) { G[u].pb(edge.size()); edge.pb({u,v,w,0}); G[v].pb(edge.size()); edge.pb({v,u,0,0}); } ll dis[MAXN],pre[MAXN]; void update() { ll p=t; while(p!=s) { ll e=pre[p]; edge[e].flow+=dis[t]; edge[e^1].flow-=dis[t]; p=edge[e].u; } ans+=dis[t]; } bool bfs() { memset(dis,0,sizeof(dis)); dis[s]=1e16; queue<ll> q; q.push(s); while(q.size()) { ll u=q.front(); q.pop(); for(auto e:G[u]) { ll v=edge[e].v; if(!dis[v]&&edge[e].cap>edge[e].flow) { dis[v]=min(dis[u],edge[e].cap-edge[e].flow); pre[v]=e; q.push(v); } } if(dis[t]) break; } if(dis[t]) { update(); return true; } return false; } int main() { scanf("%lld%lld%lld%lld",&n,&m,&s,&t); for(ll i=1;i<=m;i++) { ll u,v,w; scanf("%lld%lld%lld",&u,&v,&w); add(u,v,w); } while(bfs()); printf("%lld",ans); return 0; } ``` ### 最小割问题 [最小割 - OI Wiki](https://oi-wiki.org/graph/flow/min-cut/) ### 最小费用最大流问题 [费用流 - OI Wiki](https://oi-wiki.org/graph/flow/min-cost/) # 杂项 ## 模拟退火 [模拟退火 - OI Wiki](https://oi-wiki.org/misc/simulated-annealing/) 设当前状态为 $S$,当前温度为 $T$,状态 $S$ 对应能量为 $E(S)$: 则可令新状态为 $S'=S+\text{rand}()\cdot T$,$\Delta E=E(S')-E(S)$。 则接受新解概率为 $P(\Delta E)= \begin{cases} 1 & \Delta E<0 \\ e^{-\frac{\Delta E}{T}} & \Delta E\ge0 \end{cases}$。