模板

· · 算法·理论

其他

快速IO(P10815)

快读

inline int read()
{
    int x = 0;
    int flag = 1;
    char c = getchar();
    while(!isdigit(c))
    {
        if(c == '-')
        flag = -1;
        c = getchar();
    }
    while(isdigit(c))
    {
        x = x * 10 + (c - '0');
        c = getchar();
    }
    return x * flag;
}//快读
template<typename T> void read(T&x)
{
    char c;int sign = 1;x = 0;
    // 判断是否是负数,以及去掉前面多余的字符
    do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c)); 
    do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
    x *= sign;
}

快出

inline void put(long long d)
{
    if(d < 0)
    putchar('-'),d = -d;
    if(d > 9) put(d / 10);
    putchar((d % 10) + '0');
}

单调队列(P1886)

#include<bits/stdc++.h>
using namespace std;
template<typename T> void rd(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e6 + 66;
int n,k,a[N],p[N],q[N],tail,head = 1;
void maxx()
{
    head = 1;tail = 0;
    for(int i = 1;i <= n;i ++)
    {
        while(tail >= head && a[i] >= q[tail]) tail --;
        q[++ tail] = a[i];
        p[tail] = i;
        while(i - p[head] >= k) head ++;
        if(i >= k) cout << q[head] << " ";
    }
}
void minn()
{
    head = 1;tail = 0;
    for(int i = 1;i <= n;i ++)
    {
        while(tail >= head && a[i] <= q[tail]) tail --;
        q[++ tail] = a[i];
        p[tail] = i;
        while(i - p[head] >= k) head ++;
        if(i >= k)  cout << q[head] << " ";
    }
}
int main()
{
    rd(n),rd(k);
    for(int i = 1;i <= n;i ++)
        rd(a[i]);
    minn();
    putchar('\n');
    maxx();
    return 0;
}

单调栈(P5788)

#include<bits/stdc++.h>
using namespace std;
template<typename T> void rd(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 3e6 + 66;
int a[N],n,p[N];
stack<int> s;

int main()
{
    rd(n);
    for(int i = 1;i <= n;i ++)
        rd(a[i]);
    s.push(0);
    for(int i = n;i >= 1;i --)
    {
        while(a[i] >= a[s.top()] && s.size() > 1) 
            s.pop();
        p[i] = s.top();
        s.push(i);
    }
    for(int i = 1;i <= n;i ++)
        cout << p[i] << " ";
    return 0;
}

分块(P13976)

区间加法,单点查值

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 3e5 + 66;
ll n, a[N], tag[N], len, pos[N];
void build()
{
    for(int i = 1;i <= n;i ++) pos[i] = (i - 1) / len + 1;
}
void add(ll l, ll r, ll c)
{
    if(pos[l] == pos[r]) {for(int i = l;i <= r;i ++) a[i] += c;return ;}
    for(int i = l;pos[i] == pos[l];i ++) a[i] += c;
    for(int i = r;pos[i] == pos[r];i --) a[i] += c;
    for(int i = pos[l] + 1;i <= pos[r] - 1;i ++) tag[i] += c;
}
ll query(int r){return a[r] + tag[pos[r]];}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> n;len = sqrt(n);
    for(int i = 1;i <= n;i ++) cin >> a[i];
    build();
    for(int i = 1;i <= n;i ++)
    {
        ll od, l, r, c;cin >> od >> l >> r >> c;
        if(od == 0) add(l, r, c);
        else cout << query(r) << '\n';
    }
    return 0;
}

区间加法,询问区间内小于某个值 x 的元素个数(P13977)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 3e5 + 66;
ll n, a[N], tag[N], len, pos[N], sor[N];
#define L(i) ((i - 1) * len + 1)
#define R(i) min(n, len * i)
void build()
{
    for(int i = 1;i <= n;i ++) pos[i] = (i - 1) / len + 1;
    for(int i = 1;i <= n;i ++) sor[i] = a[i];
    for(int i = 1;i <= pos[n];i ++) sort(sor + L(i), sor + 1 + R(i));
}
void add(ll l, ll r, ll c)
{
    if(pos[l] == pos[r]) {for(int i = l;i <= r;i ++) a[i] += c;for(int i = L(pos[l]);i <= R(pos[l]);i ++) sor[i] = a[i];sort(sor + L(pos[l]), sor + R(pos[l]) + 1);return ;}
    for(int i = l;pos[i] == pos[l];i ++) a[i] += c;
    for(int i = r;pos[i] == pos[r];i --) a[i] += c;
    for(int i = pos[l] + 1;i <= pos[r] - 1;i ++) tag[i] += c;
    for(int i = L(pos[l]); i <= R(pos[l]);i ++) sor[i] = a[i];
    for(int i = L(pos[r]); i <= R(pos[r]);i ++) sor[i] = a[i];
    sort(sor + L(pos[l]), sor + R(pos[l]) + 1);sort(sor + L(pos[r]), sor + R(pos[r]) + 1);
}
ll query(ll l, ll r, ll c)
{
    c = c * c;ll res = 0;
    if(pos[l] == pos[r])
    {
        for(int i = l;i <= r;i ++) res += a[i] + tag[pos[i]] < c;
        return res;
    }
    for(int i = l;pos[i] == pos[l];i ++) res += a[i] + tag[pos[i]] < c;
    for(int i = r;pos[i] == pos[r];i --) res += a[i] + tag[pos[i]] < c;
    for(int i = pos[l] + 1; i <= pos[r] - 1;i ++) res += lower_bound(sor + L(i), sor + R(i) + 1, c - tag[i]) - sor - L(i);
    return res;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> n;len = sqrt(n);
    for(int i = 1;i <= n;i ++) cin >> a[i];
    build();
    for(int i = 1;i <= n;i ++)
    {
        ll od, l, r, c;cin >> od >> l >> r >> c;
        if(od == 0) add(l, r, c);
        else cout << query(l, r, c) << '\n';
    }
    return 0;
}

区间加法,询问区间内某个值 x 的前驱(比其小的最大元素)(P13978)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 3e5 + 66;
ll n, a[N], tag[N], len, pos[N], sor[N];
#define L(i) ((i - 1) * len + 1)
#define R(i) min(n, len * i)
void build()
{
    for(int i = 1;i <= n;i ++) pos[i] = (i - 1) / len + 1;
    for(int i = 1;i <= n;i ++) sor[i] = a[i];
    for(int i = 1;i <= pos[n];i ++) sort(sor + L(i), sor + 1 + R(i));
}
void add(ll l, ll r, ll c)
{
    if(pos[l] == pos[r]) {for(int i = l;i <= r;i ++) a[i] += c;for(int i = L(pos[l]);i <= R(pos[l]);i ++) sor[i] = a[i];sort(sor + L(pos[l]), sor + R(pos[l]) + 1);return ;}
    for(int i = l;pos[i] == pos[l];i ++) a[i] += c;
    for(int i = r;pos[i] == pos[r];i --) a[i] += c;
    for(int i = pos[l] + 1;i <= pos[r] - 1;i ++) tag[i] += c;
    for(int i = L(pos[l]); i <= R(pos[l]);i ++) sor[i] = a[i];
    for(int i = L(pos[r]); i <= R(pos[r]);i ++) sor[i] = a[i];
    sort(sor + L(pos[l]), sor + R(pos[l]) + 1);sort(sor + L(pos[r]), sor + R(pos[r]) + 1);
}
ll query(ll l, ll r, ll c)
{
    ll res = -0x3f3f3f3f3f;
    if(pos[l] == pos[r])
    {
        for(int i = l;i <= r;i ++) res = max(res, a[i] + tag[pos[i]] < c ? a[i] + tag[pos[i]] : -0x3f3f3f3f3f);
        return res == -0x3f3f3f3f3f ? -1 : res;
    }
    for(int i = l;pos[i] == pos[l];i ++) res = max(res, a[i] + tag[pos[i]] < c ? a[i] + tag[pos[i]] : -0x3f3f3f3f3f);
    for(int i = r;pos[i] == pos[r];i --) res = max(res, a[i] + tag[pos[i]] < c ? a[i] + tag[pos[i]] : -0x3f3f3f3f3f);
    for(int i = pos[l] + 1; i <= pos[r] - 1;i ++) 
    {
        auto p = lower_bound(sor + L(i), sor + R(i) + 1, c - tag[i]) - 1;
        res = max(res, p != sor + L(i) - 1 ? *p + tag[i]: -0x3f3f3f3f3f);
    }
    return res == -0x3f3f3f3f3f ? -1 : res;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> n;len = sqrt(n);
    for(int i = 1;i <= n;i ++) cin >> a[i];
    build();
    for(int i = 1;i <= n;i ++)
    {
        ll od, l, r, c;cin >> od >> l >> r >> c;
        if(od == 0) add(l, r, c);
        else cout << query(l, r, c) << '\n';
    }
    return 0;
}

倍增

ST表(P3865)

#include<bits/stdc++.h>
using namespace std;
template<typename T> inline void rd(T &x)
{
    x = 0;char c;long long f = 1;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const long long N = 1e5 + 66;
long long f[N][20],o1[N],n,m,a[N];
inline void st_open()
{
    for(long long i = 1;i <= n;i ++) f[i][0] = a[i];
    for(long long j = 1;j <= o1[n];j ++)
        for(long long i = 1;i <= n - (1 << j) + 1;i ++)
            f[i][j] = max(f[i][j - 1],f[i + (1 << (j - 1))][j - 1]);
}
inline long long st_query(long long l,long long r)
{
    long long k = o1[r - l + 1];
    return max(f[l][k],f[r - (1 << k) + 1][k]);
}
signed main()
{
    rd(n),rd(m);
    for(long long i = 1;i <= n;i ++)
        o1[i] = log2(i),rd(a[i]);
    st_open();
    for(long long i = 1;i <= m;i ++)
    {
        long long l,r;rd(l),rd(r);
        printf("%lld\n",st_query(l,r));
    }
    return 0;   
}

快速幂(P1226)

 long long qpow(long long x,long long y)
 {
    long long w = 1;
    while(y)
    {
        if(y & 1)w = w * x % p;
        y >>= 1;x = x * x % p;
     }
     return w;
 }

dp

LIS 和 LCS

最长上升子序列(LIS)(B3637)

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 50;
long long s[N],top;
long long a[N],ans,n,ma = -1;
int main()
{
    cin >> n;
    for(int i = 1;i <= n;i ++)
    cin >> a[i];
    for(int i = 1;i <= n;i ++)
    {
        s[i] = 1;
        for(int j = 1;j < i;j ++)
        if(a[j] < a[i])
        s[i] = max(s[j] + 1,s[i]);
        ma = max(s[i],ma);
    }
    cout << ma << endl;
}

最长上升子序列(LIS)(已优化)

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 50;
long long s[N],top;
long long a[N],ans,n;
int left_boundary(int x)
{
    int l = 1,r = top;
    while(l <= r)
    {
        int mid = l + (r - l) / 2;
        if(s[mid] >= x)
        r = mid - 1;
        else
        l = mid + 1;
    }
    return l;
}
int main()
{
    cin >> n;
    for(int i = 1;i <= n;i ++)
    cin >> a[i];
    s[++ top] = a[1];
    for(int i = 2;i <= n;i ++)
    {
        if(s[top] >= a[i])
            s[left_boundary(a[i])] = a[i];
        else
        s[++ top] = a[i];
    }
    cout << top << endl;
}

最长公共子序列(LCS)(已优化)(P1439)

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+66;
int dp[N],a[N],b[N],c[N];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        c[a[i]]=i;
    }
    for(int i=1;i<=n;i++)
    {
        cin>>b[i];
    }
    dp[1]=c[b[1]];
    int k=1;
    for(int i=2;i<=n;i++)
    {
        if(c[b[i]]>dp[k])
        {
            k++;
            dp[k]=c[b[i]];
        }
        else
        {
            dp[lower_bound(dp+1,dp+1+k,c[b[i]])-dp]=c[b[i]];
        }
    }
    cout<<k<<endl;
    return 0;
}

背包问题

01背包(P1048)

#include<bits/stdc++.h>
using namespace std;
const int N=1100;
int dp[N],v[N],w[N];
int n,s;
int main()
{
    memset(dp,0,sizeof(dp));
    cin>>n>>s;
    for(int i=1;i<=n;i++)
    {
        cin>>w[i]>>v[i];
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=s;j>=w[i];j--)
        {
            dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
        }
    }
    cout<<dp[s];
    return 0;
}

完全背包(P1616)

#include<bits/stdc++.h>
using namespace std;
const int N=1100;
int v[N],w[N],dp[N];
int main()
{
    int n,s;
    cin>>n>>s;
    for(int i=1;i<=n;i++)
    {
        cin>>w[i]>>v[i];
        for(int j=w[i];j<=s;j++)
        {
            dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
        }
    }
    cout<<dp[s];
 } 

多重背包

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 1e6 + 10;
ll dp[N], V[N], W[N], n, m, tot, M;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> n >> M;
    for(int i = 1;i <= n;i ++)
    {
        ll v, w;
        cin >> v >> w >> m;
        ll now = 1;
        while(m >= now)
        {
            V[++ tot] = v * now;
            W[tot] = w * now;
            m -= now;
            now <<= 1;
        }
        if(m) V[++ tot] = v * m, W[tot] = w * m;
    }
    for(int i = 1;i <= tot;i ++)
        for(int j = M;j >= W[i];j --)
            dp[j] = max(dp[j], dp[j - W[i]] + V[i]);
    cout << dp[M] << '\n';
    return 0;
}

混合背包(P1833)

#include<bits/stdc++.h>
using namespace std;
const int N = 210000;
const int M = 210000;
int v[N], w[N], dp[M], s[N], vi, wi, si, k = 0, n, c, h1, h2, m1, m2;
string ss, s1;bool f;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> ss >> s1;
    for(int i = 0;i < ss.size();i ++)
    {
        if(ss[i] == ':') {f = 1;continue;}
        if(!f) h1 = h1 * 10 + ss[i] - '0';
        else m1 = m1 * 10 + ss[i] - '0';
    }
    for(int i = 0;i < s1.size();i ++)
    {
        if(s1[i] == ':') {f = 0;continue;}
        if(f) h2 = h2 * 10 + s1[i] - '0';
        else m2 = m2 * 10 + s1[i] - '0';
    }
    h2 = h2 - h1 - (m2 < m1);
    m2 = m2 - m1 > 0? m2 - m1 : m2 - m1 + 60;
    c = h2 * 60 + m2;
    cin >> n;
    for(int i = 1;i <= n;i ++)
    {
        cin >> wi >> vi >> si;
        if(si > 0)
        {
            int t = 1;
            while(t <= si)
            {
                k ++;
                w[k] = t * wi;v[k] = t * vi;s[k] = -1;
                si = si - t;t *= 2;
            }
            if(si)
            {
                k ++;
                w[k] = si * wi;v[k] = si * vi;s[k] = -1;
            }
        }
        else
        {
            k ++;v[k] = vi;w[k] = wi;s[k] = si;
        }
    }
    for(int i = 1;i <= k;i ++)
    {
        if(s[i] == -1) for(int j = c;j >= w[i];j --) dp[j] = max(dp[j],dp[j - w[i]] + v[i]);
        else for(int j = w[i];j <= c;j ++) dp[j] = max(dp[j],dp[j - w[i]] + v[i]);
    }
    cout << dp[c];
    return 0;
}

二维费用背包

#include<bits/stdc++.h> 
using namespace std;
const int N = 1050;
const int M = 1000;
int v,w,dp[M][M],s;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int vk,wk,n;
    cin>>n>>vk>>wk;
    for(int i = 1;i <= n;i ++)
    {
        cin >>v >>w >>s;
        for(int j = vk;j >= v;j --)
            for(int k = wk;k >= w;k --)
            dp[j][k]=max(dp[j][k],dp[j - v][k - w] + s);
    }

    cout<<dp[vk][wk];
    return 0;
}

分组背包

#include<bits/stdc++.h>
using namespace std;
const int N = 2100;
int dp[N];
inline int read()
{
    int x = 0;
    int flag = 1;
    char c = getchar();
    while(!isdigit(c))
    {
        if(c == '-')
        flag = -1;
        c = getchar();
    }
    while(isdigit(c))
    {
        x = x * 10 + (c - '0');
        c = getchar();
    }
    return x * flag;
}//快读
int n,m;
struct ccs{
    int w,v,group;
}a[N];
int main()
{
    vector<pair<int,pair<int,int> > > o;
    //m[i].first -> group m[i].first.first -> v second -> w
    int m = read(),n = read();
    for(int i = 1;i <= n;i ++)
        a[i].w = read(),a[i].v = read(),a[i].group = read();
    for(int i = 1;i <= n;i ++)
    {
        bool p = 0;
        pair<int,int> q;
        for(auto s:o)
        {
            if(s.first == a[i].group)
            {
                q.first = s.second.first;
                q.second = s.second.second;
                p = 1;
            }
        }
        for(int j = m;j >= a[i].w;j --)
        {
            if(p)
            {
                if(j >= q.second)
                    dp[j] = max(dp[j],dp[j - a[i].w] + a[i].v - q.first);
                else
                    dp[j] = max(dp[j],dp[j - a[i].w] + a[i].v);
            }
            else
            {
                dp[j] = max(dp[j],dp[j - a[i].w] + a[i].v);
                o.push_back(make_pair(a[i].group,make_pair(a[i].v,a[i].w)));
            }
         } 
    }

    cout << dp[m];
    return 0;
}

图论

单源最短路

SPFA

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5+50,M=5e5+50;
int n,m,s;
int head[N],nxt[M],to[M],w[M],tot;
void add(int x,int y,int val)
{
    to[tot]=y;
    nxt[tot]=head[x];
    w[tot]=val;
    head[x]=tot++;
}
long long d[N];//表示从s出发到x节点的最短路长度 
int vis[N];//vis[x]表示是否选取过x这个节点,更新最短路 
queue<int> q;
void dij()
{
    int x; 
    for(int i=0;i<=n;i++)
    {
        d[i]=INT_MAX;
    }
    d[s]=0;
    q.push(s);
    while(!q.empty())
    {
        int x=q.front();q.pop();vis[x] = 0;
        for(int i=head[x];~i;i=nxt[i])
        {
            if(d[to[i]]>d[x]+w[i])
            {
                d[to[i]]=d[x]+w[i];
                if(!vis[to[i])
                {
                     vis[to[i]] = 1;
                     q.push(to[i]);
                }
            }
        }
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        cin>>x>>y>>c;
        add(x,y,c);
    }
    dij();
    for(int i=1;i<=n;i++)
    {
        cout<<d[i]<<" ";
    }
    return 0; 
 }

dijkstra非堆优化

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+50,M=5e5+50;
int n,m,s;
int head[N],nxt[M],to[M],w[M],tot;
void add(int x,int y,int val)
{
    to[tot]=y;
    nxt[tot]=head[x];
    w[tot]=val;
    head[x]=tot++;
}
long long d[N];//表示从s出发到x节点的最短路长度 
int vis[N];//vis[x]表示是否选取过x这个节点,更新最短路 
void dij(int x)
{
    for(int i=0;i<=n;i++)
        d[i]=INT_MAX;
    d[x]=0;
    int y;
    for(int i=1;i<n;i++)
    {
        y=0;
        for(int j=1;j<=n;j++)
            if(!vis[j]&&d[j]<d[y])
                y=j;
        vis[y]=1;
        for(int j=head[y];~j;j=nxt[j])
            if(d[to[j]]>d[y]+w[j])
                d[to[j]]=d[y]+w[j];
    }
}
int main()
{
    memset(head,-1,sizeof(head)/4);
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        cin>>x>>y>>c;
        add(x,y,c);
    }
    dij(s);
    for(int i=1;i<=n;i++)
        cout<<d[i]<<" ";
    return 0; 
}

dijkstra 堆优化

#include<bits/stdc++.h>
using namespace std; 
const int N = 5e5+66;
typedef long long LL;
int n,s,m;
int head[N],to[N],nxt[N],w[N],tot;
LL d[N];
bool vis[N];
void add(int x,int y,int v)
{
    to[tot] = y;
    nxt[tot] = head[x];
    w[tot] = v;
    head[x] = tot ++;
}
priority_queue<pair<LL,int> > q;
void dij()
{
    d[s] = 0;
    q.push(make_pair(-d[s],s));
    while(!q.empty())
    {
        int x = q.top().second;
        q.pop();
        if(vis[x])
        continue;
        vis[x] = 1;
        for(int i = head[x];~i;i = nxt[i])
            if(d[to[i]] > d[x] + w[i])
            {
                d[to[i]] = d[x] + w[i];
                q.push(make_pair(-d[to[i]],to[i]));
            }
    }
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    memset(head,-1,sizeof(head));
    cin >> n >> m >> s;
    int x,y,k;
    for(int i = 1;i <= m;i ++)
    {
        cin >> x >> y >> k;
        add(x,y,k);
    }
    for(int i = 1;i <= n;i ++)
    d[i] = INT_MAX;
    dij();
    for(int j = 1;j <= n;j ++)
        cout << d[j] << " ";
    return 0;   
}

多源最短路

floyd

#include<bits/stdc++.h>
using namespace std;
const int N=505;
int n,m,dp[N][N];
int main()
{
    memset(dp,0x3f,sizeof(dp));
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,w;
        cin>>x>>y>>w;
        dp[x][y]=min(dp[x][y],w);//可能存在重边 
        dp[y][x]=min(dp[y][x],w);
    }
    for(int i=1;i<=n;i++)
    {
        dp[i][i]=0;
    }
    for(int k=1;k<=n;k++)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]);
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cout<<dp[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

johnson 全源最短路

板子题

#include<bits/stdc++.h>
using namespace std;
#define int long long
template<typename T> void read(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 3e3 + 10;
vector<pair<int,int> > tu[N];
bool vis[N];
int f[N][N],h[N],d[N],n,m,ans[N],ru[N];
inline bool spfa()
{
    for(int i = 1;i <= n;i ++) h[i] = 1e9;
    h[0] = 0;
    queue<int> q;
    vis[0] = true;
    q.push(0);
    while(!q.empty())
    {
        int x = q.front();q.pop();
        vis[x] = false;
        for(auto i : tu[x])
            if(h[i.first] > h[x] + i.second)
            {
                h[i.first] = h[x] + i.second;
                if(!vis[i.first])
                {
                    vis[i.first] = true;
                    q.push(i.first);
                    ru[i.first] ++;
                    if(ru[i.first] == n + 1) return false;
                }
            }
    }
    for(int i = 1;i <= n;i ++)
        for(auto &k : tu[i])
            k.second += h[i] - h[k.first];
    return true;
}
void dijkstra(int b)
{
    memset(vis,false,sizeof(vis));
    for(int i = 1;i <= n;i ++) d[i] = 1e9;
    d[b] = 0;
    priority_queue<pair<int,int> > di;
    di.push(make_pair(-d[b],b));
    while(!di.empty())
    {
        int t = di.top().second;di.pop();
        if(vis[t]) continue;vis[t] = 1;
        for(auto i : tu[t])
            if(d[i.first] > d[t] + i.second)
            {
                d[i.first] = d[t] + i.second;
                di.push(make_pair(-d[i.first],i.first));
            }
//      for(int i = 1;i <= n;i ++)  f[b][i] = d[i] + h[i] - h[b];
    }
}
signed main()
{
    read(n),read(m);
    for(int i = 1;i <= m;i ++)
    {
        long long u,v,val;
        read(u),read(v),read(val);
        tu[u].push_back(make_pair(v,val));
    }
    for(int i = 1;i <= n;i ++)
        tu[0].push_back(make_pair(i,0));
    if(!spfa()) {cout << -1; return 0;}
    for(int i = 1;i <= n;i ++)
    {
        int ans = 0;
        dijkstra(i);
        for(int j = 1;j <= n;j ++)
        {
            if(d[j] == 1e9) ans += j * 1e9;
            else ans += j * (d[j] + h[j] - h[i]);
        }
        cout << ans << endl;
    }

    return 0;
}

非板子

#include<bits/stdc++.h>
using namespace std;
#define int long long
template<typename T> void read(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e3 + 10;
vector<pair<int,int> > tu[N];
bool vis[N];
int f[N][N],h[N],d[N],n,m,ans[N],ru[N];
inline bool spfa()
{
    for(int i = 1;i <= n;i ++) h[i] = 1e9;
    h[0] = 0;
    queue<int> q;
    vis[0] = true;
    q.push(0);
    while(!q.empty())
    {
        int x = q.front();q.pop();
        vis[x] = false;
        for(auto i : tu[x])
            if(h[i.first] > h[x] + i.second)
            {
                h[i.first] = h[x] + i.second;
                if(!vis[i.first])
                {
                    vis[i.first] = true;
                    q.push(i.first);
                    ru[i.first] ++;
                    if(ru[i.first] == n + 1) return false;
                }
            }
    }
    for(int i = 1;i <= n;i ++)
        for(auto &k : tu[i])
            k.second += h[i] - h[k.first];
    return true;
}
void dijkstra(int b)
{
    memset(vis,false,sizeof(vis));
    for(int i = 1;i <= n;i ++) d[i] = 1e9;
    d[b] = 0;
    priority_queue<pair<int,int> > di;
    di.push(make_pair(-d[b],b));
    while(!di.empty())
    {
        int t = di.top().second;di.pop();
        if(vis[t]) continue;vis[t] = 1;
        for(auto i : tu[t])
            if(d[i.first] > d[t] + i.second)
            {
                d[i.first] = d[t] + i.second;
                di.push(make_pair(-d[i.first],i.first));
            }
        for(int i = 1;i <= n;i ++)  f[b][i] = d[i] + h[i] - h[b];
    }
}
signed main()
{
    read(n),read(m);
    for(int i = 1;i <= m;i ++)
    {
        long long u,v,val;
        read(u),read(v),read(val);
        tu[u].push_back(make_pair(v,val));
    }
    for(int i = 1;i <= n;i ++)
        tu[0].push_back(make_pair(i,0));
    if(!spfa()) {cout << -1; return 0;}
    for(int i = 1;i <= n;i ++)
        dijkstra(i);
    for(int i = 1;i <= n;i ++)
        for(int j = 1;j <= n;j ++)
            cout << f[i][j] << (j == n ? '\n' : ' ');
    return 0;
}

tarjan

求强连通分量

#include<bits/stdc++.h>
using namespace std;
template<typename T> inline void rd(T &x)
{
    x = 0;char c;int f = 1;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e6 + 66;
int nxt[N],head[N],to[N],dfn[N],low[N],vis[N],color[N];
stack<int> s;
int n,m,deep = 0,tot,clol;
void add(int x,int y)
{
    nxt[tot] = head[x];
    to[tot] = y;
    head[x] = tot ++;
}
void tarjan(int u)
{
    dfn[u] = low[u] = ++ deep;vis[u] = 1;s.push(u);
    for(int i = head[u];~i;i = nxt[i])
    {
        int v = to[i];
        if(!dfn[v])
        {
            tarjan(v);
            low[u] = min(low[u],low[v]);
        }
        else if(vis[v])
            low[u] = min(low[u],dfn[v]);
    }
    if(dfn[u] == low[u])
    {
        color[u] = ++clol;
        vis[u] = 0;
        while(s.top() != u)
        {
            color[s.top()] = clol;
            vis[s.top()] = 0;
            s.pop();
        }
        s.pop();
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    rd(n),rd(m);
    while(m --)
    {
        int x,y;
        rd(x),rd(y);
        add(x,y);
    }
    for(int i = 1;i <= n;i ++)
        if(!dfn[i])
            tarjan(i);
    cout << clol << endl;
    for(int i = 1;i <= n;i ++)
    {
        if(!vis[i])
        {
            for(int j = i;j <= n;j ++)
                if(color[j] == color[i]) printf("%d ",j),vis[j] = 1;
            putchar('\n');
        }

    }
    return 0;
}

割点

#include<bits/stdc++.h>
using namespace std;
template<typename T> inline void rd(T &x)
{
    x = 0;char c;int f = 1;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e6 + 66;
int nxt[N],head[N],to[N],dfn[N],low[N];
bool vis[N],color[N];
int n,m,deep = 0,tot,clol;
void add(int x,int y)
{
    nxt[tot] = head[x];
    to[tot] = y;
    head[x] = tot ++;
}
void tarjan(int u,int fa)
{
    dfn[u] = low[u] = ++ deep;vis[u] = 1;
    int child = 0;
    for(int i = head[u];~i;i = nxt[i])
    {
        int v = to[i];
        if(!vis[v])
        {
            child ++;
            tarjan(v,u);
            low[u] = min(low[u],low[v]);
            if(fa != u && low[v] >= dfn[u] && !color[u])
            {
                color[u] = 1;
                clol ++;
            }
        }
        else if(v != fa)
            low[u] = min(low[u],dfn[v]);
    }
    if(fa == u && child >= 2 && !color[u])
    {
        color[u] = 1;
        clol ++;
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    rd(n),rd(m);
    while(m --)
    {
        int x,y;
        rd(x),rd(y);
        add(x,y);
        add(y,x);
    }
    for(int i = 1;i <= n;i ++)
        if(!vis[i])
            tarjan(i,i);
    cout << clol << endl;
    for(int i = 1;i <= n;i ++)
        if(color[i]) cout << i << " ";
    return 0;
}

割边(无重边)

#include<bits/stdc++.h>
using namespace std;
template<typename T> inline void rd(T &x)
{
    x = 0;char c;int f = 1;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e6 + 66;
int nxt[N],head[N],to[N],dfn[N],low[N],father[N];
bool vis[N],color[N];
int n,m,deep = 0,tot,clol;
set<pair<int,int> > s;
void add(int x,int y)
{
    nxt[tot] = head[x];
    to[tot] = y;
    head[x] = tot ++;
}
void tarjan(int u,int fa)
{
    father[u] = fa;
    dfn[u] = low[u] = ++ deep;vis[u] = 1;
    for(int i = head[u];~i;i = nxt[i])
    {
        int v = to[i];
        if(!vis[v])
        {
            tarjan(v,u);
            low[u] = min(low[u],low[v]);
            if(low[v] > dfn[u])
            {
                color[v] = 1;
                clol ++;
            }
        }
        else if(v != fa)
            low[u] = min(low[u],dfn[v]);
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    rd(n),rd(m);
    while(m --)
    {
        int x,y;
        rd(x),rd(y);
        add(x,y);
        add(y,x);
    }
    for(int i = 1;i <= n;i ++)
        if(!vis[i])
            tarjan(i,i);
    for(int i = 1;i <= n;i ++)
        if(color[i]) 
            s.insert({min(father[i],i),max(father[i],i)});
    for(auto v:s)
    {
        cout << v.first << " " << v.second << endl;
    }
    return 0;
}

割边(有重边)

#include<bits/stdc++.h>
using namespace std;
template<typename T> inline void rd(T &x)
{
    x = 0;char c;int f = 1;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 1e6 + 66;
int nxt[N],head[N],to[N],dfn[N],low[N],father[N];
bool vis[N],color[N];
int n,m,deep = 0,tot,clol;
set<pair<int,int> > s;
void add(int x,int y)
{
    nxt[tot] = head[x];
    to[tot] = y;
    head[x] = tot ++;
}
void tarjan(int u,int fa)
{
    bool f = 0;
    father[u] = fa;
    dfn[u] = low[u] = ++ deep;vis[u] = 1;
    for(int i = head[u];~i;i = nxt[i])
    {
        int v = to[i];
        if(!vis[v])
        {
            tarjan(v,u);
            low[u] = min(low[u],low[v]);
            if(low[v] > dfn[u])
            {
                color[v] = 1;
                clol ++;
            }
        }
        else
        {
            if(v != fa || f) low[u] = min(low[u],dfn[v]);
            else f = 1;
        } 
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    rd(n),rd(m);
    while(m --)
    {
        int x,y;
        rd(x),rd(y);
        add(x,y);
        add(y,x);
    }
    for(int i = 1;i <= n;i ++)
        if(!vis[i])
            tarjan(i,i);
    for(int i = 1;i <= n;i ++)
        if(color[i]) 
            s.insert({min(father[i],i),max(father[i],i)});
    for(auto v:s)
    {
        cout << v.first << " " << v.second << endl;
    }
    return 0;
}

点双

#include<bits/stdc++.h>
using namespace std;
constexpr int N = 5e5 +66;
int n, m;
int dfn[N], low[N], tot, top, sta[N], con;
bool insta[N],iscp[N];
vector<int> G[N], ans[N];
void tarjan(int u, int fa)
{
    sta[++ top] = u;dfn[u] = low[u] = ++ tot;//用栈记录
    int son = 0;
    for(auto v : G[u])
    {
        if(v == fa) continue;//不可走回去
        if(!dfn[v])
        {
            son ++;
            tarjan(v,u);
            low[u] = min(low[u], low[v]);//和往常一样
            if(low[v] >= dfn[u])//如果没法到上边,则u为割点
            {
                con ++;
                iscp[u] = 1;//标记
                while(sta[top] != v) ans[con].push_back(sta[top --]);//因为点双有重复,u的其他点可能会被误归入点双,所以只到v
                ans[con].push_back(v);top --;//删掉v
                ans[con].push_back(u);//放入u
            }
        }
        else low[u] = min(low[u], dfn[v]);

    }
    if(fa == u && son == 1)  iscp[u] = 0;//多判断一下
    if(fa == u && son == 0) ans[++ con].push_back(u);
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= m;i ++)
    {
        int u, v;cin >> u >> v;
        G[u].push_back(v), G[v].push_back(u);
    }
    for(int i = 1;i <= n;i ++) if(!dfn[i]) top = 0, tarjan(i,i);
    cout << con << '\n';    
    for(int i = 1;i <= con;i ++)
    {
        cout << ans[i].size();
        for(auto p : ans[i]) cout << ' ' << p;
        cout << '\n';
    }
    return 0;
}

最小生成树

kruskal

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+50,M=5e5+50;
int n,m,su,sz[N];
struct NN{
    int u,v,w;
    bool operator <(NN k) const
    {
        return w<k.w;
    }
}e[M];
int p[N];
int find(int x)
{
    return p[x]==x?x:p[x]=find(p[x]);
}//查找祖先 
void kruskal()
{
    sort(e+1,e+1+m);//排序 
    for(int i=1;i<=n;i++)
    {
        p[i]=i;//每个点一个子树,根都是自己 
        sz[i]=1;
    }//并查集 
    for(int i=1;i<=m;i++)
    {
        int x=find(e[i].u);
        int y=find(e[i].v);
        if(x==y) 
        continue;
        p[x]=y;//合并 
        su+=e[i].w;
        sz[y]+=sz[x];
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
        cin>>e[i].u>>e[i].v>>e[i].w;
    kruskal();
    if(sz[find(1)]!=n)
        cout<<"orz";
    else
    cout<<su;   
    return 0; 
 }

prim(未优化)

#include<bits/stdc++.h>
using namespace std;
const int N = 5e3 + 66,INF = 0x3f3f3f3f; 
vector<pair<int,int> > G[N];
int d[N],n,m,ans;
bool vis[N];
void prim()
{
    memset(d,0x3f,sizeof(d));
    memset(vis,0,sizeof(vis));
    d[1] = 0;
    for(int i = 1;i < n;i ++)
    {
        int x = 0;
        for(int j = 1;j <= n;j ++)
            if(!vis[j] && (x == 0 || d[j] < d[x]))
                x = j;
        vis[x] = 1;
        for(auto v:G[x])
            if(!vis[v.first])
                d[v.first] = min(d[v.first],v.second);
    }
}
int main()
{
    cin >> n >> m;
    for(int i = 1;i <= m;i ++)
    {
        int x,y,z;
        cin >> x >> y >> z;
        G[x].push_back(make_pair(y,z));
        G[y].push_back(make_pair(x,z));
    }
    prim();
    for(int i = 2;i <= n;i ++)
    if(d[i] != INF)
        ans += d[i];
    else
    {
        cout << "orz" << endl;
        return 0;
    }
    cout << ans << endl; 
    return 0;
}

prim(优化)

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+50,M=5e5+50;
int n,m,s;
int head[N],nxt[M],to[M],w[M],tot;
void add(int x,int y,int val)
{
    to[tot]=y;
    nxt[tot]=head[x];
    w[tot]=val;
    head[x]=tot++;
}
long long d[N],su; 
int vis[N];//vis[x]表示是否选取过x这个节点,更新最短路 
priority_queue<pair<long long,int> >q;
void prim()
{
    int x; 
    for(int i=0;i<=n;i++)
        d[i]=INT_MAX;
    d[1]=0;
    q.push(make_pair(-d[1],1));
    for(int i=1;i<=n;i++)
    {
        while(!q.empty()&&vis[q.top().second])
            q.pop();
        if(q.empty())
        {
            su=-1;
            break;
        }
        x=q.top().second;
        q.pop();
        vis[x]=1;su+=d[x];
        for(int j=head[x];~j;j=nxt[j])
            if(d[to[j]]>w[j])
            {
                d[to[j]]=w[j];
                q.push(make_pair(-d[to[j]],to[j]));
            }
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        cin>>x>>y>>c;
        add(x,y,c);
        add(y,x,c);
    }
    prim();
    if(su==-1)
    {
        cout<<"orz";
        return 0;
    }
    cout<<su;
    return 0; 
 }

负环

#include<bits/stdc++.h>
using namespace std;
#define int long long
template<typename T> void read(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 3e3 + 10;
vector<pair<int,int> > tu[N];
bool vis[N];
int h[N],n,m,ru[N],q;
inline void spfa()
{
    for(int i = 1;i <= n;i ++) h[i] = LONG_LONG_MAX,vis[i] = 0,ru[i] = 0;
    h[1] = 0;queue<int> q;vis[1] = true;q.push(1);
    while(!q.empty())
    {
        int x = q.front();q.pop();
        vis[x] = false;
        for(auto i : tu[x])
            if(h[i.first] > h[x] + i.second)
            {
                h[i.first] = h[x] + i.second;
                if(!vis[i.first])
                {
                    vis[i.first] = true;
                    q.push(i.first);
                    ru[i.first] ++;
                    if(ru[i.first] == n + 1) {cout << "YES" << endl;return ;}
                }
            }
    }
    cout << "NO" << endl;
}
signed main()
{
    read(q);
    while(q --)
    {
        read(n),read(m);
        for(int i = 1;i <= n;i ++) tu[i].clear();
        for(int i = 1;i <= m;i ++)
        {
            long long u,v,val;
            read(u),read(v),read(val);
            if(val >= 0)
            {
                tu[u].push_back(make_pair(v,val));
                tu[v].push_back(make_pair(u,val));
            }
            else
                tu[u].push_back(make_pair(v,val));
        }
        spfa();
    }
    return 0;
}

传递闭包

#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 66;
int n,t,dp[N][N];
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0); 
    cin >> n;
    for(int i = 1;i <= n;i ++)
        for(int j = 1;j <= n;j ++)
            cin >> dp[i][j];
    for(int k = 1;k <= n;k ++)
        for(int i = 1;i <= n;i ++)
            for(int j = 1;j <= n;j ++)
                dp[i][j] = dp[i][j] | (dp[i][k] & dp[k][j]);
    for(int i = 1;i <= n;i ++)
        for(int j = 1;j <= n;j ++)
            cout << dp[i][j] << (j == n ? '\n' : ' ');
    return 0;
}

差分约束

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 5e3 + 66;
ll dis[N], in[N], n, m, out[N];
bool vis[N];
vector<pair<ll, ll> > G[N];
bool SPFA()
{
    for(int i = 1;i <= n;i ++) dis[i] = INT_MAX;
    queue<int> q;
    vis[0] = 1;q.push(0);in[0] ++;dis[0] = 0;
    while(!q.empty())
    {
        int x = q.front();q.pop();vis[x] = 0;
        for(auto [to, val] : G[x])
            if(dis[to] > dis[x] + val)
            {
                dis[to] = dis[x] + val;
                if(!vis[to])
                {
                    in[to] ++;
                    if(in[to] > n) return 1;
                    q.push(to);vis[to] = 1;
                }
            }
    }
    return 0; 
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i ++) G[0].push_back({i, 0});
    for(int i = 1;i <= m;++ i)
    {
        ll x, y, v;cin >> x >> y >> v;
        G[y].push_back({x, v});out[y] ++;
    }
    if(SPFA()) cout << "NO";
    else
    {
//        for(int i = 1;i <= n;i ++) if(dis[i] == INT_MAX) {cout << "NO" << '\n';return 0;}
        for(int i = 1;i <= n;i ++) cout << dis[i] << ' ';
    }
    return 0;
}

欧拉路径

#include<bits/stdc++.h>
using namespace std;
template<typename T> void rd(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const int N = 2e5 + 11;
int n,m,st = 1,cntst,cnten,tot;
int in[N],out[N],ans[N],del[N];
vector<int> G[N];
void add(int x,int y)
{
    G[x].push_back(y);
    in[y] ++,out[x] ++;
}
void dfs(int x)
{
    for(int i = del[x];i < G[x].size();i = del[x])
        if(G[x][i] != 0)
        {
            del[x] = i + 1;
            dfs(G[x][i]);
        }
    ans[++ tot] = x;
}
int main()
{
    rd(n),rd(m);
    for(int i = 1;i <= m;i ++)
    {
        int x,y;
        rd(x),rd(y);
        add(x,y);
    }
    bool f = 0;
    for(int i = 1;i <= n;i ++)
    {
        if(in[i] != out[i])
        {
            f = 1;
            if(out[i] - in[i] == 1) 
                cntst ++,st = i;
            else if(in[i] - out[i] == 1)
                cnten ++;
            else
            {
                cout << "No" << endl;
                return 0;
            }
        }
    }
    if(!(cntst == 1 && cntst == cnten) && f)
    {
        cout << "No" << endl;
        return 0;
    }
    for(int i = 1;i <= n;i ++)  sort(G[i].begin(),G[i].end());
    dfs(st);
    for(int i = tot;i >= 1;i --)
        cout << ans[i] << " " ;
    return 0;
}

二分图最大匹配

#include<bits/stdc++.h>
using namespace std;
constexpr int N = 5e5 +66;
int n, m;
int dfn[N], low[N], tot, top, sta[N], con;
bool insta[N],iscp[N];
vector<int> G[N], ans[N];
void tarjan(int u, int fa)
{
    sta[++ top] = u;dfn[u] = low[u] = ++ tot;//用栈记录
    int son = 0;
    for(auto v : G[u])
    {
        if(v == fa) continue;//不可走回去
        if(!dfn[v])
        {
            son ++;
            tarjan(v,u);
            low[u] = min(low[u], low[v]);//和往常一样
            if(low[v] >= dfn[u])//如果没法到上边,则u为割点
            {
                con ++;
                iscp[u] = 1;//标记
                while(sta[top] != v) ans[con].push_back(sta[top --]);//因为点双有重复,u的其他点可能会被误归入点双,所以只到v
                ans[con].push_back(v);top --;//删掉v
                ans[con].push_back(u);//放入u
            }
        }
        else low[u] = min(low[u], dfn[v]);

    }
    if(fa == u && son == 1)  iscp[u] = 0;//多判断一下
    if(fa == u && son == 0) ans[++ con].push_back(u);
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= m;i ++)
    {
        int u, v;cin >> u >> v;
        G[u].push_back(v), G[v].push_back(u);
    }
    for(int i = 1;i <= n;i ++) if(!dfn[i]) top = 0, tarjan(i,i);
    cout << con << '\n';    
    for(int i = 1;i <= con;i ++)
    {
        cout << ans[i].size();
        for(auto p : ans[i]) cout << ' ' << p;
        cout << '\n';
    }
    return 0;
}

字符串

KMP

#include<bits/stdc++.h>
using namespace std;
inline int read()
{
    int x = 0,fl = -1;
    char c = getchar();
    while(!isdigit(c))
    {
        if(c == '-')
            fl = -1;
        c = getchar();
    }
    while(isdigit(c))
    {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return x * fl;
}
const int N = 1e6 + 66;
char a[N],b[N];
int ne[N];
int main()
{
    cin >> a + 1 >> b + 1;
    ne[1] = 0;
    int n = strlen(b + 1),m = strlen(a + 1);
    for(int i = 2,j = 0;i <= n;i ++)
    {
        while(j > 0 && b[i] != b[j + 1]) j = ne[j];
        if(b[i] == b[j + 1]) j ++;
        ne[i] = j;
    }
    for(int i = 1,j = 0;i <= m;i ++)
    {
        while(j > 0 && (j == n || a[i] != b[j + 1])) j = ne[j];
        if(a[i] == b[j + 1]) j ++;
        if(j == n) cout << (i - n + 1) << endl;
    }
    for(int i = 1;i <= n;i ++)
        cout << ne[i] << " ";
    return 0;
 } 

哈希

(题太多了,此处给的是哈希表)

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int HA = 131,N = 1e6 + 10,Mod = 1e6 + 3;
char s[N];
ULL e[N],ne[N],idx;
int h[Mod];
ULL gethash(char s[]){
    ULL r = 0;
    for(int i = 1;s[i];i ++)
        r = r * HA + s[i];
    return r;
}
void insert(ULL x)
{
    int v = x % Mod;
    idx ++;
    e[idx] = x;
    ne[idx] = h[v];
    h[v] = idx;
}
bool query(ULL x)
{
    int v = x % Mod;
    for(int i = h[v];i;i = ne[i])
        if(e[i] == x)
            return true;
    return false;
}
int main()
{
    int n;
    cin >> n;
    int ans = 0;
    for(int i = 1;i <= n;i ++)
    {   
        cin >> s + 1;
        if(i == 1 || !query(gethash(s)))
        {
            ans ++;
            insert(gethash(s));
        }
    }
    cout << ans << endl;
    return 0;
}

树同构

O(nlogS)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
constexpr int N = 1100, bas = 161;
vector<int> G[N];
vector<pair<int, int> > o;
ll t, n, tot;
map<ull, int> mp;
int dfs(int rot, int fa)
{
    vector<int> a = {-1};
    for(auto p : G[rot]) if(p != fa) a.push_back(dfs(p, rot));
    sort(a.begin(), a.end());
    ull res = 0;
    for(auto p : a) res = res * bas + p;
    if(!mp[res]) mp[res] = ++tot;
    return mp[res];
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> t;
    for(int i = 1;i <= t;i ++)
    {
        cin >> n;ll root = 0;
        for(int i = 0;i <= n;i ++) G[i].clear();
        for(int i = 1;i <= n;i ++)
        {
            int a;cin >> a;
            if(a == 0) {root = i;continue;}
            G[a].push_back(i), G[i].push_back(a);

        }
        int ans = INT_MAX;bool f = 0;
//      ans = dfs(root, 0);
        for(int i = 1;i <= n;i ++) ans = min(dfs(i, 0), ans);
        for(auto p : o) if(p.second == ans){f = 1;cout << p.first << '\n';break;}
        if(!f) {cout << i << '\n';o.push_back({i, ans});}
    }
    return 0;
}

O(nSlogS)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
constexpr int N = 1100, bas = 161;
vector<int> G[N];
vector<pair<int, int> > o;
ll t, n, tot;
map<vector<int>, int> mp;
int dfs(int rot, int fa)
{
    vector<int> a = {-1};
    for(auto p : G[rot]) if(p != fa) a.push_back(dfs(p, rot));
    sort(a.begin(), a.end());
    if(!mp[a]) mp[a] = ++tot;
    return mp[a];
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> t;
    for(int i = 1;i <= t;i ++)
    {
        cin >> n;ll root = 0;
        for(int i = 0;i <= n;i ++) G[i].clear();
        for(int i = 1;i <= n;i ++)
        {
            int a;cin >> a;
            if(a == 0) {root = i;continue;}
            G[a].push_back(i), G[i].push_back(a);

        }
        int ans = INT_MAX;bool f = 0;
//      ans = dfs(root, 0);
        for(int i = 1;i <= n;i ++) ans = min(dfs(i, 0), ans);
        for(auto p : o) if(p.second == ans){f = 1;cout << p.first << '\n';break;}
        if(!f) {cout << i << '\n';o.push_back({i, ans});}
    }
    return 0;
}

Tire

前缀个数

#include<bits/stdc++.h>
using namespace std;
const int N = 3e6;
int tree[N][100],tot = 1,n,m,t,cnt[N];
char s[N];
template<typename T> void read(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
void insert(char s[])
{
    int len = strlen(s), p = 1;
    for(int k = 0;k < len;k ++)
    {
        int ch = s[k] - '0';
        if(!tree[p][ch]) tree[p][ch] = ++tot;
        p = tree[p][ch];
        cnt[p] ++;
    }
}
int query(char s[])
{
    int len = strlen(s),p = 1;
    for(int k = 0;k < len;k ++)
    {
        int ch = s[k] - '0';
        if(!tree[p][ch]) return 0;
        p = tree[p][ch];
    }
    return cnt[p];
}
int main()
{
    read(t);
    while(t --)
    {
        for(int i = 0;i <= tot;i ++)
            for(int j = 0;j <= 122;j ++)
                tree[i][j] = 0;
        for(int i = 0;i <= tot;i ++)
            cnt[i] = 0;
        tot = 1;
        read(n),read(m);
        for(int i = 1;i <= n;i ++)
        {
            scanf("%s",s);
            insert(s);
        }
        for(int i = 1;i <= m;i ++)
        {
            scanf("%s",s);
            cout << query(s) << endl;
        }
    }
    return 0;
}

是否存在该字符串

#include<bits/stdc++.h>
using namespace std;
const int N = 3e6;
int tree[N][100],tot = 1,n,m,t;
char s[N];
bool en[N];
template<typename T> void read(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
void insert(char s[])
{
    int len = strlen(s), p = 1;
    for(int k = 0;k < len;k ++)
    {
        int ch = s[k] - '0';
        if(!tree[p][ch]) tree[p][ch] = ++tot;
        p = tree[p][ch];
    }
    en[p] = 1;
}
bool query(char s[])
{
    int len = strlen(s),p = 1;
    for(int k = 0;k < len;k ++)
    {
        int ch = s[k] - '0';
        if(!tree[p][ch]) return 0;
        p = tree[p][ch];
    }
    return en[p];
}
int main()
{
    read(t);
    while(t --)
    {
        for(int i = 0;i <= tot;i ++)
            for(int j = 0;j <= 122;j ++)
                tree[i][j] = 0;
        for(int i = 0;i <= tot;i ++)
            en[i] = 0;
        tot = 1;
        read(n),read(m);
        for(int i = 1;i <= n;i ++)
        {
            scanf("%s",s);
            insert(s);
        }
        for(int i = 1;i <= m;i ++)
        {
            scanf("%s",s);
            cout << query(s) << endl;
        }
    }
    return 0;
}

AC自动机

简单版(出现与否)

#include<bits/stdc++.h>
using ll = long long;
using namespace std;
constexpr int N = 1e6 + 66;
struct Trie{
    int son[30], over, fail;
}trie[N];
int n, tot;
string s;
void insert(string s1)
{
    int p = 1;
    for(int i = 0;i < s1.size();i ++)
    {
        int ch = s[i] - 'a' + 1;
        if(!trie[p].son[ch])trie[p].son[ch] = ++ tot;
        p = trie[p].son[ch];
    }
    trie[p].over ++;
}
void getFail()
{
    for(int i = 1;i <= 26;i ++) trie[0].son[i] = 1;
    queue<int> q;
    q.push(1), trie[1].fail = 0;
    while(!q.empty())
    {
        int u = q.front();q.pop();
        for(int i = 1;i <= 26;i ++)
        {
            int v = trie[u].son[i], fail = trie[u].fail;//取儿子和fafail
            if(!v) {trie[u].son[i] = trie[fail].son[i];continue;}//若没有儿子,就直接将儿子定义为 fafail 的儿子,减少运算量
            else trie[v].fail = trie[fail].son[i];//否则就是两个儿子是 fail
            q.push(v);//如果有儿子才放入儿子
        }
    }
}
ll query(string s1)
{
    int u = 1, ans = 0;
    for(int i = 0;i < s.size();i ++)
    {
        int v = s[i] - 'a' + 1, k;k = trie[u].son[v];//取儿子
        while(k > 1 && trie[k].over != -1)//找在这个点的 fail
        {
            ans += trie[k].over, trie[k].over = -1;
            k = trie[k].fail;
        }
        u = trie[u].son[v];
    }
    return ans ;//返回
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> n;tot = 2;
    for(int i = 1;i <= n;i ++) cin >> s, insert(s);
    getFail();
    cin >> s;
    cout << query(s) << '\n';
    return 0;
}

简单版2(出现次数)

#include<bits/stdc++.h>
using ll = long long;
using namespace std;
constexpr int N = 1e5 + 66;
struct Trie{
    int son[30], over, fail;
}trie[N];
ll n, tot, vis[N];
string s[N], t;
void clear()
{
    for(int i = 0;i <= tot;i ++) memset(trie[i].son, 0, sizeof(trie[i].son)), trie[i].over = trie[i].fail = 0;
    for(int i = 1;i <= n;i ++) vis[i] = 0;
    tot = 1;
}
void insert(string s1, int num)
{
    int p = 1;
    for(int i = 0;i < s1.size();i ++)
    {
        int ch = s1[i] - 'a' + 1;
        if(!trie[p].son[ch])trie[p].son[ch] = ++ tot;
        p = trie[p].son[ch];
    }
    trie[p].over = num;//因为是出现次数,所以可以重复出现,记录是哪一个字符串即可
}
void getFail()
{
    for(int i = 1;i <= 26;i ++) trie[0].son[i] = 1;
    queue<int> q;
    q.push(1), trie[1].fail = 0;
    while(!q.empty())
    {
        int u = q.front();q.pop();
        for(int i = 1;i <= 26;i ++)
        {
            int v = trie[u].son[i], fail = trie[u].fail;//取儿子和fafail
            if(!v) {trie[u].son[i] = trie[fail].son[i];continue;}//若没有儿子,就直接将儿子定义为 fafail 的儿子,减少运算量
            else trie[v].fail = trie[fail].son[i];//否则就是两个儿子是 fail
            q.push(v);//如果有儿子才放入儿子
        }
    }
}
ll query(string s1)
{
    int u = 1, ans = 0;
    for(int i = 0;i < s1.size();i ++)
    {
        int v = s1[i] - 'a' + 1, k;k = trie[u].son[v];//取儿子
        while(k > 1)//找在这个点的 fail
        {
            if(trie[k].over) vis[trie[k].over] ++; //记录更新次数
            k = trie[k].fail;
        }
        u = trie[u].son[v];
    }
    return ans ;//返回
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    while(1)
    {
        cin >> n;
        if(n == 0) break;
        clear();
        for(int i = 1;i <= n;i ++) cin >> s[i], insert(s[i], i);
        getFail();
        cin >> t;
//      cout << query(t) << '\n';
        query(t);
        ll ans = 0;
        for(int i = 1;i <= n;i ++) ans = max(vis[i], ans);
        cout << ans << '\n';
        for(int i = 1;i <= n;i ++) if(vis[i] == ans){cout << s[i] << '\n';}

    }
    return 0;
}

Manacher

#include<bits/stdc++.h>
using namespace std;
constexpr int N = 3e7 + 66;
char s[N];
int r[N], n, ans;
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    s[++ n] = '^', s[++ n] = '|';
    char c = getchar();
    for(;isalpha(c);c = getchar()) s[++ n] = c, s[++ n] = '|';
    s[++ n] = '$';
    for(int i = 1, j = 0, m = 0;i <= n;i ++)
    {
        if(i <= j) r[i] = min(r[2 * m - i], j - i + 1);
        while(s[i + r[i]] == s[i - r[i]]) r[i] ++;
        if(i + r[i] >= j) j = i + r[i] - 1, m = i;
    }
    for(int i = 1;i <= n;i ++) ans = max(ans, r[i] - 1);
    cout << ans << '\n';
    return 0;
 }

树形结构

树的直径

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 66;
vector<int> G[N];
int n,ans,deep[N],fa[N];
void dfs(int x)
{
    if(deep[x] > deep[ans]) ans = x;
    for(auto i : G[x])
    {
        if(i != fa[x])
        {
            fa[i] = x;
            deep[i] = deep[x] + 1;
            dfs(i);
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n - 1;i ++)
    {
        int u,v;
        cin >> u >> v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    dfs(1);
    memset(deep,0,sizeof(deep));
    memset(fa,0,sizeof(fa));
    dfs(ans);
    cout << deep[ans] << '\n';
    return 0;
}

树的重心

P1395 会议

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 66;
vector<int> e[N];
int n,sz[N],m[N],ans;//sz 为以任意一点为根,每个点子树大小 m 是以每一个点为根最大的子树大小
void dfs(int root,int fa)
{
    sz[root] = 1;
    for(auto p : e[root])
        if(p != fa)
        {
            dfs(p,root);
            sz[root] += sz[p];
        }
}
void dfss(int root,int fa)
{
    m[root] = n - sz[root];
    for(auto p : e[root])
        if(p != fa)
        {
            m[root] = max(m[root],sz[p]);
            dfss(p,root);   
        }
}
void dfsss(int root,int fa,int deep)
{
    ans += deep;
    for(auto p : e[root]) if(p != fa) dfsss(p,root,deep + 1);
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i = 1;i < n;i ++)
    {
        int u,v;cin >> u >> v;
        e[u].push_back(v);e[v].push_back(u);
    }
    dfs(1,0);
    dfss(1,0);
    int mi = INT_MAX,od;
    for(int i = 1;i <= n;i ++) if(mi > m[i]) mi = m[i],od = i;
    dfsss(od,0,0);
    cout << od << " " << ans << '\n';
    return 0;
}

LCA

倍增法

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 66;
int head[N],to[N],nxt[N];
int n,m,s,tot,fa[N][21],now,deep[N];
inline void add(int u,int v)
{
    nxt[tot] = head[u];
    to[tot] = v;
    head[u] = tot ++;
}
inline void dfs(int root)
{
    for(int i = head[root]; ~i;i = nxt[i])
        if(to[i] != fa[root][0])
        {
            deep[to[i]] = deep[root] + 1;
            fa[to[i]][0] = root;
            dfs(to[i]);
        }
}
inline int lca(int u,int v)
{
    if(deep[u] < deep[v]) swap(u,v); 
    for(int i = 20;i >= 0;i --)
        if(deep[u] - deep[v] >= (1 << i))
            u = fa[u][i];
    if(u == v) return u;
    for(int i = 20;i >= 0;i --)
        if(fa[u][i] != fa[v][i])
            u = fa[u][i],v = fa[v][i];
    return fa[u][0];
}
int main()
{
    memset(head,-1,sizeof(head));
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m >> s;
    for(int i = 1;i <= n - 1;i ++)
    {
        int u,v;cin >> u >> v;
        add(u,v);add(v,u);
    }
    dfs(s);
    for(int j = 1;j <= 20;j ++)
        for(int i = 1;i <= n;i ++)
            fa[i][j] = fa[fa[i][j - 1]][j - 1];
    while(m --)
    {
        int u,v;cin >> u >> v;
        cout << lca(u,v) << '\n';
    }
    return 0;
}

树链剖分

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 66;
vector<int> e[N];
int n,m,s,sz[N],ma[N],dep[N],f[N],tp[N],ans;//sz 子树大小 ma 重儿子编号 dep 深度 f 父亲 x 重链的上端点
void dfs(int root,int fa)
{
    dep[root] = dep[fa] + 1;sz[root] = 1;f[root] = fa;
    for(auto p : e[root])
        if(p != fa)
        {
            dfs(p,root);
            sz[root] += sz[p];
            if(sz[p] > sz[ma[root]]) ma[root] = p;
        }
}//预处理深度 子树大小 父亲 重儿子
void dfs2(int root,int top)
{
    tp[root] = top;
    if(ma[root]) dfs2(ma[root],top);
    for(auto p : e[root]) if(p != f[root] && p != ma[root]) dfs2(p,p);
}//求重链
int lca(int x,int y)
{
    while(tp[x] != tp[y])
    {
        if(dep[tp[x]] > dep[tp[y]]) x = f[tp[x]];
        else y = f[tp[y]];
    }
    if(dep[x] < dep[y]) return x;
    return y;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m >> s;
    for(int i = 1;i < n;i ++)
    {
        int u,v;cin >> u >> v;
        e[u].push_back(v);e[v].push_back(u);
    }
    dfs(s,0);
    dfs2(s,s);
    while(m --)
    {
        int x,y;cin >> x >> y;
        cout << lca(x,y) << '\n';
    }
    return 0;
}

tarjan求

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 66;
vector<int> e[N];
vector<pair<int,int> >q[N];
int n,s,m,f[N],ans[N];
bool ins[N];
int find(int x){return f[x] == x ? x : f[x] = find(f[x]);}
void dfs(int root,int fa)
{
    ins[root] = 1;
    for(auto y : q[root])
        if(ins[y.first])
            ans[y.second] = find(y.first);
    for(auto p : e[root])
        if(p != fa)
        {
            dfs(p,root);
            f[p] = root;
        }
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m >> s;
    for(int i = 1;i <= n;i ++) f[i] = i;
    for(int i = 1;i < n;i ++)
    {
        int x,y,z;cin >> x >> y;
        e[x].push_back(y),e[y].push_back(x);
    }
    for(int i = 1;i <= m;i ++)
    {
        int x,y;cin >> x >> y;
        q[y].push_back({x,i});q[x].push_back({y,i});
    }
    dfs(s,s);
    for(int i = 1;i <= m;i ++) cout << ans[i] << '\n';
    return 0;
}

堆

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 66;
long long a[N << 2],q,tot;
void change(int id,int od)
{
    if(od == 1)
    {
        if(a[id] > a[id >> 1] || id == 1) return ;
        swap(a[id],a[id >> 1]);
        change(id >> 1,1);
    }
    else
    {
        if(id * 2 > tot) return ;
        int p = id;
        if(a[p] > a[id * 2]) p = id * 2;
        if(a[p] > a[id * 2 + 1] && id * 2 + 1 <= tot) p = id * 2 + 1;
        swap(a[id],a[p]);
        if(p != id) change(p,2);
    }
}
void insert(int x)
{
    a[++ tot] = x;
    change(tot,1);
}
void pop()
{
    swap(a[1],a[tot --]);
    change(1,2);
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> q;
    while(q --)
    {
        int od,x;
        cin >> od;
        if(od == 1){cin >> x;insert(x);}
        else if(od == 2) cout << a[1] << '\n';
        else pop();
    } 
    return 0;
}

并查集

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 66;
int n,m,fa[N];
int find(int x)
{
    if(x == fa[x]) return fa[x];
    return fa[x] = find(fa[x]);
}
void merge(int x,int y)
{
    int xx = find(x),yy = find(y);
    if(xx != yy) fa[xx] = yy;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i ++) fa[i] = i;
    for(int i = 1;i <= m;i ++)
    {
        int x,y,z;
        cin >> z >> x >> y;
        if(z == 1) merge(x,y);
        else 
        {
            if(find(x) == find(y)) cout << "Y\n" ;
            else cout << "N\n";
        }
    }
}

树状数组

模板1

#include<bits/stdc++.h>
using namespace std;
template<typename T> void rd(T&x)
{
    char c;int sign = 1;x = 0;
    // 判断是否是负数,以及去掉前面多余的字符
    do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c)); 
    do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
    x *= sign;
}
const int N = 5e5 + 66;
long long a[N],n,m;
int lowbit(int x){return x & -x;}
void add(int o,int v)
{
    for(int i = o;i <= n;i = i + lowbit(i))
        a[i] += v;
}
long long query(int x)
{
    long long res = 0;
    for(int i = x;i >= 1;i = i - lowbit(i))
        res += a[i];
    return res;
}
int main()
{
    rd(n),rd(m);
    for(int i = 1;i <= n;i ++)
    {
        int x;
        rd(x);
        add(i,x);
    }
    for(int i = 1;i <= m;i ++)
    {
        int od,x,y;
        rd(od),rd(x),rd(y);
        if(od == 1) add(x,y);
        else cout << (query(y) - query(x - 1)) << endl;
    }
    return 0;   
}

广义扫描线

#include<bits/stdc++.h>
using namespace std;
constexpr int N = 2e6 + 66;
int n, m, a[N], ans[N];
struct node{
    int zf, idx, k;
};
vector<node> qst[N];
struct Bit{
    int c[N];
    int lowbit(int x){return x & -x;}
    void add(int x, int k){for(;x < N;x += lowbit(x)) c[x] += k;}
    int query(int x){int res = 0;for(;x > 0;x -= lowbit(x)) res += c[x];return res;}
    int P(int l,int r){return query(r) - query(l - 1);}
}bit;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i ++) cin >> a[i];//以值做位置 
    for(int i = 1;i <= m;i ++) 
    {
        int l, r, k;cin >> l >> r >> k;
        qst[l - 1].push_back({-1, i, k});qst[r].push_back({1, i, k});//记录长度 
    }
    for(int i = 1;i <= n;i ++)
    {
        bit.add(a[i], 1);//加入这个位置 
        for(auto p : qst[i]) ans[p.idx] += p.zf * bit.query(p.k);//判断是否是减去的 
    }
    for(int i = 1;i <= m;i ++) cout << ans[i] << '\n';
    return 0;
 } 

线段树

模板1

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 1e5 + 66;
ll a[N], n, m;
struct SegmentTree{
    SegmentTree *ls, *rs;
    ll l, r, tag, val;
    SegmentTree(int l, int r, ll a[]) : l(l), r(r), val(0), tag(0)
    {
        if(l != r)
        {
            int mid = l + r >> 1;
            ls = new SegmentTree(l, mid, a), rs = new SegmentTree(mid + 1, r, a);
            pushup();
        }   
        else ls = rs = nullptr, val = a[l];
    }
    inline void pushup(){val = ls -> val + rs -> val;}
    inline bool inRange(int x, int y){return x <= l && r <= y;}
    inline bool outRange(int x, int y){return l > y || r < x;}
    inline void maketag(ll k)
    {
        val += (r - l + 1) * k;
        tag += k;
    }
    inline void pushdown()
    {
        if(tag)
        {
            ls -> maketag(tag);
            rs -> maketag(tag);
            tag = 0;
        }
    }
    inline void update(int x, int y, ll k)
    {
        if(inRange(x, y)){maketag(k);}
        else if(!outRange(x, y))
        {
            pushdown();
            ls -> update(x, y, k);rs -> update(x, y, k);
            pushup();
        }
    }
    inline ll query(int x, int y)
    {
        if(inRange(x, y)) return val;
        else if(outRange(x, y)) return 0;
        pushdown();
        return ls -> query(x, y) + rs -> query(x, y);
    }
};
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i ++) cin >> a[i];
    auto root = new SegmentTree(1, n, a);
    for(int i = 1;i <= m;i ++)
    {
        ll op, x, y;
        cin >> op >> x >> y;
        if(op == 1) 
        {
            ll val;cin >> val;
            root -> update(x, y, val);
        }
        else cout << root -> query(x, y) << '\n';
    }
    return 0;
 }

模板2

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 66;
long long n,m,a[N],mod;
struct Str{
    long long tr[N << 2],tag[N << 2],add[N << 2];
    void push_up(int k){tr[k] = tr[k << 1] + tr[k << 1 | 1];}
    void build(int l,int r,int k)
    {
        add[k] = 1;
        if(l == r){tr[k] = a[l];return ;}
        int mid = l + r >> 1;
        build(l,mid,k << 1);
        build(mid + 1,r,k << 1 | 1);
        push_up(k);
    }
    void IO_change(int l,int r,int k,long long v,long long vv)
    {
        tr[k] = (tr[k] * vv + v * (r - l + 1)) % mod;
        tag[k] = (tag[k] * vv + v) % mod;
        add[k] = (add[k] * vv) % mod;
    }
    void push_down(int l,int r,int k)
    {
        int mid = l + r >> 1;
        IO_change(l,mid,k << 1,tag[k],add[k]);
        IO_change(mid + 1,r,k << 1 | 1,tag[k],add[k]);
        tag[k] = 0;add[k] = 1;
    }
    void change(int l,int r,int k,int x,int y,long long val,long long valv)
    {
        if(x <= l && r <= y){IO_change(l,r,k,val,valv);return ;}
        push_down(l,r,k);
        int mid = l + r >> 1;
        if(x <= mid) change(l,mid,k << 1,x,y,val,valv);
        if(y > mid) change(mid + 1,r,k << 1 | 1,x,y,val,valv);
        push_up(k);
    }
    long long query(int l,int r,int k,int x,int y)
    {
        if(x <= l && r <= y) return tr[k];
        push_down(l, r, k);
        long long mid = l + r >> 1,res = 0;
        if(x <= mid) res += query(l,mid,k << 1,x,y);
        if(y > mid) res += query(mid + 1,r,k << 1 | 1,x,y);
        res %= mod;
        return res;
    }
}tree;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> m >> mod;
    for(int i = 1;i <= n;i ++) cin >> a[i];
    tree.build(1,n,1);
    for(int i = 1;i <= m;i ++)
    {
        long long od,x,y,val;
        cin >> od >> x >> y;
        if(od == 1)
        {
            cin >> val;
            tree.change(1,n,1,x,y,0,val);
        }
        else if(od == 2)
        {
            cin >> val;
            tree.change(1,n,1,x,y,val,1);
        }
        else cout << tree.query(1,n,1,x,y) << '\n';
    }
    return 0;
}

扫描线

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
constexpr int N = 1e5 + 66;
int n, bur[N * 2], tot;
struct line{
    ll xl, xr, y, k;//左 右 第几行 上还是下 
    line() = default;
    line(ll xl, ll xr, ll y, ll k): xl(xl), xr(xr), y(y), k(k){}
    friend bool operator < (line a, line b) {return a.y < b.y;}
}li[N * 2];//记录线段 
struct Segmenttree{
    ll len[N << 4], tag[N << 4], ans[N << 4];
    #define ls(u) (u * 2)
    #define rs(u) (u * 2 + 1) 
    void update(int u)
    {
        if(tag[u] > 0) ans[u] = len[u];//如果有 
        else ans[u] = ans[ls(u)] + ans[rs(u)];//否则 
    }//改变 
    void build(ll u, ll l, ll r)
    {
        len[u] = bur[r] - bur[l - 1];
        if(l == r) return ;
        int mid = l + r >> 1;
        build(ls(u), l, mid);
        build(rs(u), mid + 1, r);
    }//建树 
    void add(ll u, ll l, ll r, ll ql, ll qr, ll cag)
    {
        if(ql <= l && r <= qr)
        {
            tag[u] += cag;//标记永久化 
            update(u);
            return ;
        }
        ll mid = l + r >> 1;
        if(ql <= mid)add(ls(u), l, mid, ql, qr, cag);
        if(mid + 1 <= qr) add(rs(u), mid + 1, r, ql, qr, cag);
        update(u); 
    }//区间加 
}Seg;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i ++)
    {
        int xl, xr, yl, yr;
        cin >> xl >> yl >> xr >> yr;
        li[i] = line(xl, xr, yl, 1);
        li[i + n] = line(xl, xr ,yr, -1);//记录线段 
        bur[++ tot] = xl, bur[++ tot] = xr;//离散化 
    }
    sort(bur + 1, bur + 1 + tot);
    tot = unique(bur + 1, bur + 1 + tot) - bur - 1;
    for(int i = 1;i <= n * 2;i ++)
    {
        li[i].xl = lower_bound(bur + 1, bur + 1 + tot, li[i].xl) - bur + 1;
        li[i].xr = lower_bound(bur + 1, bur + 1 + tot, li[i].xr) - bur + 1;
    }//离散化完毕 
    sort(li + 1, li + 1 + 2 * n);
    Seg.build(1, 1, tot);
    ll ans = 0;
    for(int i = 1;i <= 2 * n;i ++)
    {
        ans += (li[i].y - li[i - 1].y) * Seg.ans[1];//与上一个线段所组成的矩形面积 (高) * 长 
        Seg.add(1, 1, tot, li[i].xl, li[i].xr - 1, li[i].k);
    }
    cout << ans << '\n';
    return 0;
 } 

动态开点线段树

#include<bits/stdc++.h>
using namespace std;
using ll = unsigned long long;
constexpr int N = 1e5 + 66;
ll n, m;
struct SegmentTree{
    SegmentTree *ls, *rs;
    int l, r;
    ll tag, val;
    SegmentTree(int l, int r) : l(l), r(r), val(0), tag(0){ls = rs = nullptr;}
    inline void pushup(){val = ls -> val + rs -> val;}
    inline bool inRange(int x, int y){return x <= l && r <= y;}
    inline bool outRange(int x, int y){return l > y || r < x;}
    inline void maketag(ll k)
    {
        val += (r - l + 1) * k;
        tag += k;
    }
    inline void pushdown()
    {
        if(!ls)
        {
            int mid = l + r >> 1;
            ls = new SegmentTree(l, mid);
            rs = new SegmentTree(mid + 1, r);
        }
        if(tag)
        {
            ls -> maketag(tag);
            rs -> maketag(tag);
            tag = 0;
        }
    }
    inline void update(int x, int y, ll k)
    {
        if(inRange(x, y)){maketag(k);}
        else if(!outRange(x, y))
        {
            pushdown();
            ls -> update(x, y, k);rs -> update(x, y, k);
            pushup();
        }
    }
    inline ll query(int x, int y)
    {
        if(inRange(x, y)) return val;
        else if(outRange(x, y)) return 0;
        pushdown();
        return ls -> query(x, y) + rs -> query(x, y);
    }
};
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> m;
    auto root = new SegmentTree(1, n);
    for(long long op, l, r, i = 1;i <= m;i ++)
    {
        cin >> op >> l >> r;
        if(!(op - 1))
        {
            ll k;cin >> k;
            root -> update(l, r, k);
        }
        else cout << root -> query(l, r) + (r + l) * (r - l + 1) / 2 << '\n';
    }
    return 0;
 }

笛卡尔树

#include<bits/stdc++.h>
using namespace std;
const int N = 1e7 + 66;
long long n,p[N],r[N],l[N];
stack<int> s;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i ++) cin >> p[i];
    s.push(0);r[0] = 1;s.push(1);
    for(int i = 2;i <= n;i ++)
    {
        while(!s.empty() && p[s.top()] > p[i])
        {
            int u = s.top();s.pop();
            int v = s.top();
            r[v] = i;r[u] = l[i];l[i] = u;
        }
        if(!s.empty()) r[s.top()] = i;
        s.push(i);
    }
    long long L = 0,R = 0;
    for(int i = 1;i <= n;i ++)
    {
        L ^= (l[i] + 1) * i;
        R ^= (r[i] + 1) * i;
    }
    cout << L << " " << R;  
    return 0;
}

数学

博弈论

NIM游戏

#include<bits/stdc++.h>
using namespace std;
inline int read()
{
    char c = getchar();
    int x = 0,fl = 1;
    while(!isdigit(c))
    {
        if(c == '-')
            fl = -1;
        c = getchar();
    }
    while(isdigit(c))
    {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return x * fl;
}
const int N = 1e4 + 65;
int a[N],cnt[2];
int main()
{
    int t;
    t = read();
    while(t --)
    {
        int n = read(),s = 0;
        for(int i = 1;i <= n;i ++)
            a[i] = read(),s ^= a[i];
        if(s == 0)
            cout << "No" << endl;
        else
            cout << "Yes" << endl;

    }
}

数论

中国剩余定理(CRT)

#include<bits/stdc++.h>
#define int __int128
using namespace std;
int n,p[120],m[120];
template<typename T> void read(T&x)
{
    char c;int sign = 1;x = 0;
    // 判断是否是负数,以及去掉前面多余的字符
    do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c)); 
    do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
    x *= sign;
}
void exgcd(int a,int b,int &x,int &y)
{
    if(b == 0){x = 1;y = 0;return ;}
    exgcd(b, a % b, y, x);
    y -= (a / b * x);
}
void print(int l)
{
    if(l / 10) print(l / 10);
    cout << (long long)(l % 10);
}
signed main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    read(n);
    int M = 1,ans = 0;
    for(int i = 1;i <= n;i ++) read(p[i]),read(m[i]),M *= p[i];
    for(int i = 1;i <= n;i ++)
    {
        int mm = M / p[i];
        int x,y;
        exgcd(p[i],mm,x,y);
        ans = (ans + m[i] * mm * y) % M;
    }
    print((ans % M + M) % M);
}

线性求逆元

#include<bits/stdc++.h>
using namespace std;
const int N = 3e6 + 66;
long long inv[N],n,p;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    cin >> n >> p;inv[1] = 1;
    for(int i = 2;i <= n;i ++) inv[i] = (p - p / i) * inv[p % i] % p;
    for(int i = 1;i <= n;i ++) cout << inv[i] << '\n'; 
}

EXgcd(有理数取余)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int mod = 19260817;
void exgcd(ll a, ll b, ll &x, ll &y)
{
    if(b == 0) {x = 1, y = 0;return ;}
    exgcd(b, a % b, y, x);
    y -= a / b * x;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    ll a = 0, b = 0, x, y;
    char c = getchar();
    while(isdigit(c)) {a = a * 10 + (c - '0'); a %= mod; c = getchar();}
    while(!isdigit(c)) c =getchar();
    while(isdigit(c)) {b = b * 10 + (c - '0'); b %= mod; c = getchar();}
    if(b == 0){cout << "Angry!\n";return 0;}
    exgcd(b, mod, x, y);
    cout << (1ll * (x + mod) % mod * a % mod) << '\n';
    return 0;
}

线性筛

#include<bits/stdc++.h>
using namespace std;
template<typename T> void rd(T &x)
{
    x = 0;int f = 1;char c;
    do{c = getchar();if(c == '-') f = -1;}while(!isdigit(c));
    do{x = x * 10 + c - '0';c = getchar();}while(isdigit(c));
    x *= f;
}
const long long N = 1e8 + 6;
long long p[N],tot;bool pr[N]; 
void Ol(long long m)
{
    for(int i = 1;i <= N;i ++) pr[i] = 1;
    pr[1] = pr[0] = 0;
    for(int i = 2;i <= m;i ++)
    {
        if(pr[i]) p[++ tot] = i;
        for(int j = 1;j <= tot;j ++)
        {
            if(p[j] * i > m) break;
            pr[p[j] * i] = 0;
            if(i % p[j] == 0) break;
        }
    }
}
long long n,q,k;
int main()
{
    rd(n);
    Ol(n);
    rd(q);
    while(q --)
    {
        rd(k);
        cout << p[k] << endl;
    }
}

组合数学

Lucas

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 2e5 + 66;
ll po[N], impo[N], n, m, p, t;
ll C(int m, int n){return (n < m ? 0 : po[n] * impo[m] % p * impo[n - m] % p);}
ll lucas(int m, int n){return (m == n || m == 0 ? 1 :  C(m % p, n % p) * lucas(m / p, n / p) % p);}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);
    cin >> t;
    while(t --)
    {
        cin >> n >> m >> p;po[0] = impo[1] = impo[0] = 1;
        for(int i = 1;i <= 2e5;i ++) po[i] = po[i - 1] * i % p;
        for(int i = 2;i <= 2e5;i ++) impo[i] = (p - p / i) * impo[p % i] % p;
        for(int i = 1;i <= 2e5;i ++) impo[i] = impo[i] * impo[i - 1] % p;
        cout << lucas(n, n + m) << '\n';
    }
    return 0;
}

线性代数

高斯消元

#include<bits/stdc++.h>
using namespace std;
struct Matrix{
    double a[110][110];
    int n,m;
    Matrix(){memset(a,0,sizeof(a));}
//  void init(){for(int i = 1;i <= n;i ++)for(int j = 1;j <= m;j ++)a[i][j] = 0;}
    Matrix operator + (Matrix B)
    {
        Matrix C;
        C.n = n,C.m = m;
        for(int i = 1;i <= n;i ++) for(int j = 1;j <= m;j ++) C.a[i][j] = a[i][j] + B.a[i][j];
        return C;
    }
    Matrix operator - (Matrix B)
    {
        Matrix C;
        C.n = n,C.m = m;
        for(int i = 1;i <= n;i ++) for(int j = 1;j <= m;j ++) C.a[i][j] = a[i][j] - B.a[i][j];
        return C;
    }
    Matrix operator * (Matrix B)
    {
        Matrix C;
        C.n = n,C.m = B.m;
        for(int i = 1;i <= n;i ++) 
            for(int j = 1;j <= C.m;j ++)
                for(int k = 1;k <= m;k ++)
                    C.a[i][j] += a[i][k] * B.a[k][j];
        return C;
    }
    Matrix& operator = (const Matrix& B)
    {
        n = B.n,m = B.m;
        for(int i = 1;i <= n;i ++)
            for(int j = 1;j <= m;j ++)
                a[i][j] = B.a[i][j];
        return *this;
    }
    inline void print()
    {
        for(int i = 1;i <= n;i ++)
            for(int j = 1;j <= m;j ++)
                cout << a[i][j] << (j == m ? '\n' : ' ');
    }   
};
int main()
{
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    int n;
    double a[110][110];
    cin >> n;
    for(int i = 1;i <= n;i ++) for(int j = 1;j <= n + 1;j ++) cin >> a[i][j];
    for(int i = 1;i <= n;i ++)//删第 i 行
    {
        int p = i;
        while(p <= n && a[p][i] == 0) p ++;//找交换的行
        if(p == n + 1)//如果没有
        {
            cout << "No Solution\n";
            return 0;
        }
        for(int j = 1;j <= n + 1;j ++) swap(a[i][j],a[p][j]);//将第 i 行与第 p 行交换
        double temp = a[i][i];//第 i 行要消元的
        for(int j = 1;j <= n + 1;j ++) a[i][j] /= temp;//求第 i 行的 j 个数和要消元的数的倍数
        for(int j = 1;j <= n;j ++)//第 j 行
        {
            if(i == j) continue;//不能删同一行
            temp = a[j][i];//第j行要删的那个数
            for(int k = 1;k <= n + 1;k ++)
                a[j][k] -= a[i][k] * temp;//全部都减去
        }
    }
    for(int i = 1;i <= n;i ++) cout << fixed << setprecision(2) << a[i][n + 1] << '\n';
    return 0;
}

矩阵快速幂

#include<bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
struct Matrix{
    long long a[110][110],n,m;
    Matrix(){memset(a,0,sizeof(a));}
    void init(){for(int i = 1;i <= n;i ++)for(int j = 1;j <= m;j ++)a[i][j] = 0;}
    Matrix operator * (Matrix B)
    {
        Matrix C;
        C.n = n,C.m = B.m;
        for(int i = 1;i <= n;i ++) 
            for(int j = 1;j <= C.m;j ++)
            {
                for(int k = 1;k <= m;k ++)
                    C.a[i][j] += (a[i][k] * B.a[k][j]) % mod;
                C.a[i][j] = C.a[i][j] % mod;
            }
        return C;
    }
    Matrix& operator = (const Matrix& B)
    {
        n = B.n,m = B.m;
        for(int i = 1;i <= n;i ++)
            for(int j = 1;j <= m;j ++)
                a[i][j] = B.a[i][j];
        return *this;
    }
    inline void print()
    {
        for(int i = 1;i <= n;i ++)
            for(int j = 1;j <= m;j ++)
                cout << a[i][j] << (j == m ? '\n' : ' ');
    }   
};
inline Matrix qpow(Matrix A, long long k)
{
    Matrix P;P.n = P.m = A.n;
    for(int i = 1;i <= P.n;i ++)P.a[i][i] = 1;
    while(k)
    {
        if(k & 1) P = P * A;
        A = A * A;
        k >>= 1;
    }
    return P;
}
int main()
{
//  freopen("P3390_1.in","r",stdin);
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    long long n,k;
    Matrix A;
    cin >> n >> k;
    A.n = A.m = n;
    for(int i = 1;i <= n;i ++) for(int j = 1;j <= n;j ++) cin >> A.a[i][j];
    qpow(A,k).print();
    return 0;
}