跳到正文

个人记录

波

wurang约 53 分钟
原文
文章信息与版本

文章信息

发布
2025年8月26日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 53 分钟

版本

  1. v3当前
  2. v2
  3. v1
trick
二项式定理 in 矩阵
∑j=0n(nj)Mj=∑j=0n(nj)Mj⋅In−j=(M+I)n \sum_{j=0}^{n} \binom{n}{j} M^j = \sum_{j=0}^{n} \binom{n}{j} M^j \cdot I^{n-j} = (M + I)^n
决策覆盖

若状态 AA 能到达集合 SS 或状态 BB,状态 BB 仅能到达集合 SS,那么状态 AA 必胜。

操作抵消

对于先手,若无论如何操作后对方可以操作使得状态的某一部分完全相同(如奇偶性),此时先手必败。

×2+1\times2+1

对于构造,若希望答案计数为 kk,此时有计数为 11 的方案,并且能找出 ×2\times2 与 +1+1 的操作方案,那么二进制拆开即可。

方案二选一

若两个方案加起来 ≤2k\leq 2k,则其中有一个方案 ≤k\leq k。

回文括号序列

记 ( 为 11,) 为 00。

记 resires_i 表示前 ii 个括号的和,有:

  1. 每个 res≥0res \geq 0。
  2. resn=0res_n = 0。
等差数列
  1. 首先max−min=(r−l)k\mathrm{max-min=(r-l)k}
  2. 其次相邻两数差的绝对值的gcd⁡\gcd是kk
  3. 区间[l,r][l,r]内的数不重复
对于二进制数 ii,求同样 11 的个数的下个数
C++
int solve(int x){return ((((x + (x & -x)) ^ x) >> 2) / (x & -x)) | (x + (x & -x));}
区间dp转移
fi,l,r=∑fi−1,l′,r′([l,r]∩[l′,r′]≠∅f_{i,l,r} = \sum f_{i-1, l', r'} ([l, r] \cap [l', r']\neq\varnothing

等价于:

prei,x=∑l≤r≤xfi,l,rpre_{i, x} = \sum_{l\leq r\leq x}f_{i, l, r}sufi,x=∑x≤l≤rfi,l,rsuf_{i, x} = \sum_{x\leq l\leq r}f_{i, l, r}fi,l,r=prei−1,m−prei−1,l−1−sufi−1,r+1f_{i, l, r} = pre_{i-1, m} - pre_{i-1, l-1} - suf_{i-1, r+1}

pre,sufpre,suf 的状态数少于 ff,考虑抛弃 ff。

prei,x=∑l≤r≤xprei−1,m−∑l≤r≤xprei−1,l−1−∑l≤r≤xsufi−1,r+1=x(x+1)2prei−1,m−∑l≤x(x−l+1)prei−1,l−1−∑r≤xr×sufi−1,r+1\begin{aligned} pre_{i, x} &= \sum_{l\leq r\leq x}pre_{i-1, m} - \sum_{l\leq r\leq x}pre_{i-1, l-1} - \sum_{l\leq r\leq x}suf_{i-1, r+1} \\ &=\frac{x(x+1)}{2}pre_{i-1,m}-\sum_{l \leq x}(x-l+1)pre_{i-1,l-1}-\sum_{r \leq x}r\times suf_{i-1, r+1} \end{aligned}sufi,x=∑x≤l≤rprei−1,m−∑x≤l≤rprei−1,l−1−∑x≤l≤rsufi−1,r+1=(m−x+1)(m−x+2)2prei−1,m−∑x≤l(m−l+1)prei−1,l−1−∑x≤r(r−x+1)sufi−1,r+1\begin{aligned} suf_{i, x} &= \sum_{x\leq l\leq r}pre_{i-1, m} - \sum_{x\leq l\leq r}pre_{i-1, l-1} - \sum_{x\leq l\leq r}suf_{i-1, r+1} \\ &=\frac{(m-x+1)(m-x+2)}{2}pre_{i-1,m}-\sum_{x\leq l}(m-l+1)pre_{i-1,l-1}-\sum_{x\leq r}(r-x+1)suf_{i-1, r+1} \end{aligned}

考虑对称性或将 pre,sufpre, suf 并排放,可用矩阵乘法优化。

插件
copy_markdown
JavaScript
// ==UserScript==
// @name         copy-markdown
// @namespace    https://github.com/LYkcul
// @description  获取页面 Markdown 源代码
// @author       BlackPanda
// @license      MIT
// @version      1.2.0
// @match        https://www.luogu.com.cn/*
// @match        https://www.luogu.com/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";
  function injectStyle() {
    var style = document.createElement("style");
    style.textContent = `
    .lcolor-var-green-3 {
        --lcolor-rgb: 82, 196, 26;
    }
    .lcolor-var-blue-3 {
        --lcolor-rgb: 52, 152, 219;
    }
    .lcolor-var-red-3 {
        --lcolor-rgb: 231, 76, 60;
    }   
    .copy-markdown-btn {
        --l-button--real-color: var(--lcolor-rgb, var(--lcolor--primary, var(--lcolor--primary, 52, 152, 219)));
        display: inline-block;
        outline: none;
        cursor: pointer;
        font-weight: inherit;
        line-height: 1.5;
        text-align: center;
        vertical-align: middle;
        border-radius: 3px;
        border: 1px solid rgb(var(--l-button--real-color));
        background: rgba(var(--l-button--real-color),0) none;
        color: rgb(var(--l-button--real-color));
        margin-right: .5em;
    }
    .copy-markdown-btn-contest {
        --l-button--real-color: var(--lcolor-rgb, var(--lcolor--primary, var(--lcolor--primary, 52, 152, 219)));
        display: inline-block;
        outline: none;
        cursor: pointer;
        font-weight: inherit;
        line-height: 1.5;
        text-align: center;
        vertical-align: middle;
        border-radius: 3px;
        border: 1px solid rgb(var(--l-button--real-color));
        background: rgb(var(--l-button--real-color));
        color: #fff;
        margin-right: .5em;
    }
    /* why no margin-right on exlg-cph??? */
    .exlg-cph + .copy-markdown-btn-contest {
        margin-left: .5em;
    }
    `;
    document.head.appendChild(style);
  }
  /*====================*/
  const routes = [
    {
      name: "article_show",
      match: (path) => /^\/(article)\/(?!mine$|_?new$)[A-Za-z0-9]+$/.test(path),
      mount: ".user-nav",
      getContent: async () => {
        let ele = document.querySelector("script#lentille-context");
        let json = JSON.parse(ele.textContent.trim());
        let url = location.href;
        if (url.endsWith("/")) url = url.slice(0, -1);
        if (
          json.template !== "article.show" ||
          json.data.article.lid !== url.split("/").pop()
        ) {
          console.log("[DEBUG] retry");
          const res = await fetch(location.href, {
            credentials: "include",
            headers: {
              "x-requested-with": "XMLHttpRequest",
              "x-lentille-request": "content-only",
            },
          });
          const html = await res.text();
          json = JSON.parse(html.trim());
        }
        console.log(json);
        const content = json.data?.article?.content || "复制失败";
        return content;
      },
    },
    {
      name: "user_detail",
      match: (path) => /^\/user\/\d+$/.test(path),
      test: (url) => !(url.hash && url.hash.length > 1 && url.hash !== "#main"),
      mount: ".user-nav",
      getContent: async () => {
        return _feInstance.currentData.user.introduction || "复制失败";
      },
      className: "lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn",
      classNameSucc: "lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn",
      classNameErr: "lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn",
    },
    {
      name: "contest_detail",
      match: (path) => /^\/contest\/\d+$/.test(path),
      test: (url) =>
        !(url.hash && url.hash.length > 1 && url.hash !== "#description"),
      mount: ".functional > .operation",
      specialMount: true,
      getContent: async () => {
        return _feInstance.currentData.contest.description || "复制失败";
      },
      className:
        "lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn-contest",
      classNameSucc:
        "lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn-contest",
      classNameErr:
        "lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn-contest",
      selfMount: ".copy-markdown-btn-contest",
    },
    {
      name: "training_detail",
      match: (path) => /^\/training\/\d+$/.test(path),
      test: (url) =>
        !(url.hash && url.hash.length > 1 && url.hash !== "#information"),
      mount: ".functional > .operation",
      specialMount: true,
      getContent: async () => {
        return _feInstance.currentData.training.description || "复制失败";
      },
      className:
        "lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn-contest",
      classNameSucc:
        "lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn-contest",
      classNameErr:
        "lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn-contest",
      selfMount: ".copy-markdown-btn-contest",
    },
  ];
  function getRoute() {
    const path = location.pathname;
    return (
      routes.find((r) => {
        return (
          (typeof r.test === "function" ? r.test(location) : true) &&
          r.match(path)
        );
      }) || null
    );
  }
  function isValidUrl() {
    return !!getRoute();
  }
  function cleanupBtn() {
    document
      .querySelectorAll("#copy-markdown-mount")
      .forEach((el) => el.remove());
  }
  async function insertBtn() {
    const route = getRoute();
    if (!route) return false;
    const nav = document.querySelector(route.mount || ".user-nav");
    if (!nav) return;
    if (nav.querySelector(".copy-markdown-btn")) return true;
    let btn = document.createElement("button");
    btn.textContent = "复制源代码";
    btn.type = "button";
    btn.id = "copy-markdown-mount";
    btn.className =
      route.className ||
      "lform-size-middle lcolor-var-blue-3 copy-markdown-btn";
    btn.addEventListener("click", async () => {
      try {
        console.log("[DEBUG] route: ", route.name);
        const content = await route.getContent();
        await navigator.clipboard.writeText(content);
        btn.textContent = "复制成功";
        btn.className =
          route.classNameSucc ||
          "lform-size-middle lcolor-var-green-3 copy-markdown-btn";
      } catch (e) {
        console.error("复制失败:", e);
        btn.textContent = "复制失败";
        btn.className =
          route.classNameErr ||
          "lform-size-middle lcolor-var-red-3 copy-markdown-btn";
      } finally {
        setTimeout(() => {
          btn.textContent = "复制源代码";
          btn.className =
            route.className ||
            "lform-size-middle lcolor-var-blue-3 copy-markdown-btn";
        }, 600);
      }
    });
    if (route.specialMount) {
      nav.insertBefore(btn, nav.lastChild.nextSibling);
    } else {
      nav.insertBefore(btn, nav.firstChild);
    }
    return true;
  }
  function handleUrlChange() {
    injectStyle();
    if (!isValidUrl()) {
      cleanupBtn();
      return;
    }
    const start = Date.now();
    const timer = setInterval(() => {
      if (!isValidUrl()) {
        clearInterval(timer);
        cleanupBtn();
        return;
      }
      if (insertBtn()) {
        clearInterval(timer);
        return;
      }
      if (Date.now() - start > 3000) clearInterval(timer);
    }, 100);
  }
  const fireUrlChange = () =>
    window.dispatchEvent(new Event("userscript:urlchange"));
  const _ps = history.pushState,
    _rs = history.replaceState;
  history.pushState = function (...a) {
    const r = _ps.apply(this, a);
    fireUrlChange();
    return r;
  };
  history.replaceState = function (...a) {
    const r = _rs.apply(this, a);
    fireUrlChange();
    return r;
  };
  window.addEventListener("popstate", fireUrlChange);
  window.addEventListener("hashchange", fireUrlChange);
  window.addEventListener("userscript:urlchange", () => {
    cleanupBtn();
    setTimeout(handleUrlChange, 0);
  });
  const init = () => handleUrlChange();
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();

板子
缺省源
C++
#include <bits/stdc++.h>
// #pragma GCC optimize(3,"Ofast","inline")
#define int long long
using namespace std;
namespace IO {
    const int LL=1<<20; char bbuf[LL],*pp1,*pp2,OOUT[LL],*pp3=OOUT; 
    #define Gc() (pp1==pp2&&(pp2=(pp1=bbuf)+fread(bbuf,1,LL,stdin),pp1==pp2)?EOF:*pp1++)
    #define Pc(x) (pp3==OOUT+LL&&(fwrite(OOUT,1,LL,stdout),pp3=OOUT),*pp3++=(x))
    struct F{~F(){fwrite(OOUT,1,pp3-OOUT,stdout);}}fff;
    template<typename T> inline void rd(T& x){x=0ll; char c=Gc(); bool xans=0; while(!isdigit(c))xans^=c=='-',c=Gc();while(isdigit(c))x=x*10+(c^48),c=Gc(); if(xans)x=-x;}inline void rd(char& c){do c=Gc();while(isspace(c));}inline void rd(string& s){s=""; char c; rd(c); do s+=c; while(!isspace(c=Gc())&&~c);}template<typename T,typename... A> inline void rd(T& x,A&... mat){rd(x),rd(mat...);}template<typename T> inline void wt(T x){if(x<0)Pc('-'),x=-x; static int s[45],t=0; do s[++t]=x%10; while(x/=10);while(t)Pc(s[t--]|48);}inline void wt(char c){Pc(c);}inline void wt(const char* s){while(*s)Pc(*s++);}inline void wt(string s){for(char c:s)Pc(c);}template<typename T,typename... A> inline void wt(T x,A... mat){wt(x),Pc(sizeof...(mat)?' ':'\n'),(wt(mat...),0);}
} using namespace IO;
#define fr(x) freopen(#x".in", "r", stdin); freopen(#x".out", "w", stdout);
#define rep(i, l, r) for(int i = (l); i <= (r); ++i)
#define urep(i, r, l) for(int i = (r); i >= (l); --i)
#define ary array <int, 3>
constexpr int inf = 0x3f3f3f3f3f3f3f3f, mod = 1000000007;
#define _ 200005

signed main()
{    
    
    return 0;
}
数据结构
单向链表模板
C++
struct Node 
{
    int data;
    Node *next;
    Node *right;
}

void insertNode(int i, Node *p) {
  Node *node = new Node;
  node->value = i;
  node->next = p->next;
  p->next = node;
}

void deleteNode(Node *p) {
  p->value = p->next->value;
  Node *t = p->next;
  p->next = p->next->next;
  delete t;
}
并查集
C++
namespace DSU
{
	int fa[_], siz[_];
	inline void init(){for(int i = 1; i < _; i++)fa[i] = i,siz[i] = 1;}
	int find(int x){return fa[x] == x ? x : fa[x] = find(fa[x]);}
	void unite(int x, int y)
	{
        x = find(x), y = find(y);
		if(x == y)return;
		if (siz[x] < siz[y]) swap(x, y);
    	siz[x] += siz[y]; 
    	fa[y] = x;
	}
};
平衡树
AVL
C++
int n, root;

struct node
{
    int l, r, h, siz, x;
}t[100005];
int cnt;

inline void upd(int p){if(p == 0)return;t[p].siz = 1 + (t[p].l ? t[t[p].l].siz : 0) + (t[p].r ? t[t[p].r].siz : 0);}
inline void upd_h(int p){if(p == 0)return;t[p].h = max((t[p].l ? t[t[p].l].h : 0), (t[p].r ? t[t[p].r].h : 0)) + 1;}

void LL_rorate(int &p)
{
    int q = t[p].l;
    t[p].l = t[q].r;
    t[q].r = p;
    t[q].siz = t[p].siz;
    upd(p);
    upd_h(p);
    upd_h(q);
    p = q;
}

void RR_rorate(int &p)
{
    int q = t[p].r;
    t[p].r = t[q].l;
    t[q].l = p;
    t[q].siz = t[p].siz;
    upd(p);
    upd_h(p);
    upd_h(q);
    p = q;
}

void LR_rorate(int &p)
{
	RR_rorate(t[p].l);
	LL_rorate(p);
}

void RL_rorate(int &p)
{
	LL_rorate(t[p].r);
	RR_rorate(p);
}

void fix(int &p)
{
	if(p == 0) return;
    if(t[t[p].l].h - t[t[p].r].h == 2)
    {
        if(t[t[t[p].l].l].h >= t[t[t[p].l].r].h) LL_rorate(p);
        else LR_rorate(p);
    }
    if(t[t[p].r].h - t[t[p].l].h == 2)
    {
        if(t[t[t[p].r].r].h >= t[t[t[p].r].l].h) RR_rorate(p);
        else RL_rorate(p);
    }
    upd(p), upd_h(p);
}

void insert(int &p, int x)
{
    if(p == 0)
    {
        p = ++cnt;
        t[p].l = t[p].r = 0;
        t[p].h = 1;
        t[p].siz = 1;
        t[p].x = x;
    }
    else if(x < t[p].x)
    {
        insert(t[p].l, x);
        fix(p);
    }
    else
    {
        insert(t[p].r, x);
        fix(p);
    }
}

void del(int &p, int x)
{
    if(p == 0) return;
    if(x < t[p].x)
        del(t[p].l, x);
    else if(x > t[p].x)
        del(t[p].r, x);
    else
    {
        if(t[p].l == 0 && t[p].r == 0) p = 0;
        else if(t[p].l == 0) p = t[p].r;
        else if(t[p].r == 0) p = t[p].l;
        else
        {
            int q = t[p].l;
            while(t[q].r) q = t[q].r;
            t[p].x = t[q].x;
            del(t[p].l, t[q].x);
        }
    }
    fix(p);
}
int query_rank(int p, int x)
{
    if(p == 0) return 0;
    if(x <= t[p].x) return query_rank(t[p].l, x);
    else return query_rank(t[p].r, x) + t[t[p].l].siz + 1;
}

int find(int p, int x)
{
    if(p == 0) return 0;
    if(x == t[t[p].l].siz + 1) return t[p].x;
    if(x <= t[t[p].l].siz) return find(t[p].l, x);
    else return find(t[p].r, x - t[t[p].l].siz - 1);
}

int pre(int p, int x)
{
    if(p == 0) return 0;
    if(t[p].x >= x) return pre(t[p].l, x);
    else 
    {
        int op = pre(t[p].r, x);
        return (op != 0 ? op : t[p].x);
    }
}

int suf(int p, int x)
{
    if(p == 0) return 0;
    if(t[p].x <= x) return suf(t[p].r, x);
    else 
    {
        int op = suf(t[p].l, x);
        return (op ? op : t[p].x);
    }
}
treap
C++
class treap
{
	int cnt;
	
	struct node
	{
	    int l, r;
	    int x, val;
	    int siz;
	}t[1000005];
	
	public:
		treap(){t[0].l = t[0].r = t[0].siz = t[0].x = t[0].val = 0;}
		int root;
		inline void upd(int p){t[p].siz = 1 + (t[p].l ? t[t[p].l].siz : 0) + (t[p].r ? t[t[p].r].siz : 0);}
		
		void l_rorate(int &p)
		{
		    int q = t[p].r;
		    t[p].r = t[q].l;
		    t[q].l = p;
		    t[q].siz = t[p].siz;
		    upd(p);
		    p = q;
		}
		
		void r_rorate(int &p)
		{
		    int q = t[p].l;
		    t[p].l = t[q].r;
		    t[q].r = p;
		    t[q].siz = t[p].siz;
		    upd(p);
		    p = q;
		}
		
		void insert(int &p, int x)
		{
		    if(p == 0)
		    {
		        p = ++cnt;
		        t[p].l = t[p].r = 0;
		        t[p].x = x;
		        t[p].val = rand();
		        upd(p);
		        return;
		    }
		    t[p].siz++;
		    if(x < t[p].x)
		    {
		        insert(t[p].l, x);
		        if(t[t[p].l].val > t[p].val) r_rorate(p);
		    }
		    else
		    {
		        insert(t[p].r, x);
		        if(t[t[p].r].val > t[p].val) l_rorate(p);
		    }
		    upd(p);
		}
		
		void erase(int &p, int x)
		{
		    if(p == 0) return ;
		    if(x < t[p].x) 
		    {
		        erase(t[p].l, x);
		        upd(p);
		    } 
		    else if(x > t[p].x) 
		    {
		        erase(t[p].r, x);
		        upd(p);
		    } 
		    else 
		    {
		        if(t[p].l == 0 || t[p].r == 0) 
		            p = (t[p].l ? t[p].l : t[p].r);
		        else 
		        {
		            if(t[t[p].l].val < t[t[p].r].val) 
		            {
		                r_rorate(p);
		                erase(t[p].r, x);
		            } 
		            else 
		            {
		                l_rorate(p);
		                erase(t[p].l, x);
		            }
		        }
		        if(p) upd(p);
		    }
		}
		
		int query_rank(int p, int x)
		{
		    if(p == 0) return 0;
		    if(x <= t[p].x) return query_rank(t[p].l, x);
		    else return query_rank(t[p].r, x) + t[t[p].l].siz + 1;
		}
		
		int find(int p, int x)
		{
		    if(p == 0) return 0;
		    if(x == t[t[p].l].siz + 1) return t[p].x;
		    if(x <= t[t[p].l].siz) return find(t[p].l, x);
		    else return find(t[p].r, x - t[t[p].l].siz - 1);
		}
		
		int pre(int p, int x)
		{
		    if(p == 0) return 0;
		    if(t[p].x >= x) return pre(t[p].l, x);
		    else 
		    {
		        int op = pre(t[p].r, x);
		        return (op ? op : t[p].x);
		    }
		}
		
		int suf(int p, int x)
		{
		    if(p == 0) return 0;
		    if(t[p].x <= x) return suf(t[p].r, x);
		    else 
		    {
		        int op = suf(t[p].l, x);
		        return (op ? op : t[p].x);
		    }
		}
}tree;
矩阵
C++
struct Matrix
{
    int x, y;
    int a[sz][sz];
    Matrix(){memset(a, 0, sizeof(a));}

    Matrix operator*(const Matrix &T) const
    {
        Matrix res; 
        res.x = x, res.y = T.y;
        int r;
        for (int i = 0; i <= x; ++i)
            for (int k = 0; k <= T.y; ++k)
            {
                r = a[i][k];
                for (int j = 0; j <= y; ++j)
                    res.a[i][j] = (res.a[i][j] + (T.a[k][j] * r));
            }
        return res;
    }

    Matrix operator^(int x) const
    {
        Matrix res, bas;
        for (int i = 0; i < sz; ++i)
            res.a[i][i] = 1;
        for (int i = 0; i < sz; ++i)
            for (int j = 0; j < sz; ++j)
                bas.a[i][j] = a[i][j];
        while (x)
        {
            if (x & 1)
                res = res * bas;
            bas = bas * bas;
            x >>= 1;
        }
        return res;
    }
}mat, base;
图论
最短路
floyd
C++
	for(int k = 1; k <= n; k++)
		for(int i = 1; i <= n; i++)
			for(int j = 1; j <= n; j++)
				/*if(i != j && i != k && j != k)*/dis[i][j]  =  min(dis[i][j],dis[i][k]+dis[k][j]);
dijkstra
C++
vector <ary> e[_];
int dis[_], vis[_];
priority_queue < ary, vector<ary>, greater<ary> >q;

void dijkstra() 
{
	memset(dis, 0x3f, sizeof(dis));
	memset(vis,0,sizeof(vis));
	dis[s] = 0;
	q.push({0, s});
	while(!q.empty())
	{
		int u = q.top()[1]; q.pop();
		if(vis[u]) continue;
		vis[u] = 1;
		for(auto [w, v] : e[u])
		{
			if (dis[v] > dis[u] + w) 
                dis[v] = dis[u] + w, q.push({dis[v], v});
		}
	}
}
spfa
C++
//spfa单源+负环
//O(nm)
const int MAXN = 1e4 + 5;
struct edge {
	int v, w;
};
vector<edge> e[MAXN];
int dis[MAXN], cnt[MAXN], vis[MAXN];
queue<int> q;
int u,v,w;
int sum;
bool spfa(int n,int s) 
{
	memset(dis, 0x3f, sizeof(dis));
	dis[s] = 0;
	q.push(s);
	while (!q.empty()) 
	{
		int u = q.front();q.pop();
		vis[u] = 1;
		for (int i = 0; i < e[u].size(); i++) 
		{
			int v = e[u][i].v, w = e[u][i] .w;
			if (dis[v] > dis[u] + w) 
			{
				dis[v] = dis[u] + w;
				cnt[v] = cnt[u] + 1;
				if (cnt[v] >= n)return false;
				// if (vis[v])continue;
				q.push(v);
				vis[v] = 1;
			}
		}
	}
	return true;
}
最小生成树
prim
C++
//prim算法,以边为基准,适用于稠密图
//与dijkstra相似,一次确定一条边
//此处为堆优化,O((n+m)log n)
struct Edge{int v,w;};
struct node
{
	int u,dis;
	bool operator>(const node& a) const { return dis > a.dis;}
}op;

int ans;
int n,m;
vector<Edge>e[105];
int a[3007][3007];
int dis[10007],vis[10007];
priority_queue<node,vector<node>,greater<node> >q;

void prim()
{
	while(!q.empty())
	{
		int now=q.top().u;q.pop();
		if(vis[now]) continue;
		vis[now]=1;
		for(int i=1;i<=n;i++)
		{
			if(i == now)continue;
			int v=i;
			if(vis[v]==0 && dis[v]>a[now][v])
			{
				dis[v]=a[now][v];
				q.push({v,dis[v]});
			}
		}
	}
}
kruskal
C++
//kruskal,瓶颈排序,m log m,适用稀疏图
//码量小,易调试
int n,m;
int ans;
struct edge
{
	int u,v,w;
}e[10005];
bool cmp(edge a,edge b){return a.w < b.w;}

int fa[150005];
int find(int x)
{
    if(fa[x] != x)
    {
        fa[x] = find(fa[x]);
    }
    return fa[x];
}
拓扑排序
C++
  for(int i = 1; i <= mp.size(); i++)
        if(!siz[i]) q.push(i);
    while(q.size())
    {
        int f = q.front();
        q.pop();
        ans ++;
        for(int j : edge[f])
        {
            siz[j]--;
            if(!siz[j]) q.push(j);
        }
    }
LCA
C++
#include <bits/stdc++.h>
#define int long long
using namespace std;

inline int rd(){int x=0,f=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}return x*f;}

constexpr int _ = 5e5 + 5;

int table[19][_];
vector<int> e[_];
int n, m, root, cnt, dfn[_];

inline int get(int x, int y) {return dfn[x] < dfn[y] ? x : y;}

void dfs(int u, int f) 
{
    dfn[u] = ++cnt;
    table[0][cnt] = f;
    for (int v : e[u])
        if (v != f) dfs(v, u);
}

int lca(int v, int u) 
{
    if (u == v) return u;
    int l = dfn[u], r = dfn[v];
    if (l > r) swap(l, r);
    ++l;
    int d = log2(r - l + 1);
    return get(table[d][l], table[d][r - (1 << d) + 1]);
}

int u, v;

signed main() 
{
    
    n = rd(), m = rd(), root = rd();
    for (int i = 2; i <= n; ++i) 
    {
        u = rd(), v = rd();
        e[u].push_back(v);
        e[v].push_back(u);
    }

    dfs(root, 0);
    
    for (int i = 1; i <= __lg(n); ++i)
        for (int j = 1; j + (1 << i) - 1 <= n; ++j)
            table[i][j] = get(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);

    while (m--)
        cout << lca(rd(), rd()) << "\n";
    return 0;
}
背包
分组
C++
	for (int k = 1; k <= ttt; k++)         
  	{
		for (int i = W; i >= 0; i--)         
		{
			for (int j = 1; j <= sum[k]; j++)  
			{
				if (i >= w[t[k][j]]) dp[i] = max(dp[i],dp[i - w[t[k][j]]] + v[t[k][j]]);
			}
		}
	}
多重
C++
    for(int i = 1; i <= N; i++)
    {
        cin>>opv>>opw>>opsum;
        int t = 1;
        while(opsum > t)
        {
            n++;
            v[n] = opv*t;
            w[n] = opw*t;
			opsum-=t;
            t*=2;
        }
        if(opsum!=0)
        {
            n++;
            v[n] = opv*opsum;
            w[n] = opw*opsum;
        }
    }
数学
组合数学
C++
struct CNM
{
    int fact[_], infact[_], inv[_];
    int qpow(int a, int b)
    {
        int res = 1;
        while (b > 0) 
        {
            a %= mod;
            if (b & 1) res = res * a % mod;
            a = a * a;
            b >>= 1;
        }
        return res;
    }
    CNM()
    {
        inv[1] = fact[0] = infact[0] = fact[1] = infact[1] = 1;
        for (int i = 2; i < _; ++i)
        inv[i] = mod - (mod / i) * inv[mod % i] % mod, fact[i] = fact[i-1] * i % mod, infact[i] = infact[i-1] * inv[i] % mod;
    }
    int C(int n, int m) {return (n >= m && n >= 0) ? fact[n] * infact[n-m] % mod * infact[m] % mod : 0;}
}C;
高斯消元
C++
namespace gss
{
    double mat[_][_], xans[_];
    const double eps = 1e-8; 
    
    int solve(int n)
    {
        bool flg = false;
        rep(i, 1, n) 
        {
            int mxi = 0;
            double maxv = 0;
            rep(j, (flg ? 1 : i), n)
            {
                if(j < i && fabs(mat[j][j] - 1) < eps) continue;
                if(fabs(mat[j][i]) > maxv)
                    maxv = fabs(mat[j][i]), mxi = j;
            }
            if(maxv < eps) { flg = true; continue; }
            if(mxi != i) swap(mat[mxi], mat[i]);
            double inv = mat[i][i];
            rep(j, i, n+1) mat[i][j] /= inv;
            rep(j, 1, n)
            {
                if(j == i) continue;
                double factor = mat[j][i];
                rep(k, i, n+1) mat[j][k] -= mat[i][k] * factor;
            }
        }
        rep(i, 1, n)
        {
            bool az = true;
            rep(j, 1, n)
                if(fabs(mat[i][j]) > eps) { az = false; break; }
            if(az && fabs(mat[i][n+1]) > eps) return -1;
        }
        if(flg) return 0;
        rep(i, 1, n) xans[i] = mat[i][n+1];
        return 1;
    }
} ;
素数筛
C++
namespace Sieve {std::bitset<_ / 2 + 1> isnt; std::vector<int> pri;void sieve(int n) {isnt.reset(); isnt[0] = 1; pri.clear();if (n >= 2) pri.emplace_back(2);for (int i = 1; i * 2 + 1 <= n; ++i) {if (!isnt[i]) {int p = i * 2 + 1;if (n / p >= p) for (int j = i * (i + 1) * 2; j * 2 + 1 <= n; j += p)isnt[j] = 1;pri.emplace_back(p);}}}inline bool check(int x) {if (x < 3) return x == 2;return (x & 1) && !isnt[x >> 1];}}
using namespace Sieve;
FastIO
C++
// #define LOCAL
namespace IO {
#ifndef LOCAL
    const int L=1<<20; char buf[L],*p1,*p2,out[L],*p3=out;
    #define Gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,L,stdin),p1==p2)?EOF:*p1++)
    #define Pc(x) (p3==out+L&&(fwrite(out,1,L,stdout),p3=out),*p3++=(x))
    struct F{~F(){fwrite(out,1,p3-out,stdout);}}f;
#else
    #define Gc() getchar()
    #define Pc(x) putchar(x)
#endif
    template<typename T> inline void rd(T& x){x=0; char c=Gc(); bool f=0; while(!isdigit(c))f^=c=='-',c=Gc();while(isdigit(c))x=x*10+(c^48),c=Gc(); if(f)x=-x;}inline void rd(char& c){do c=Gc();while(isspace(c));}inline void rd(string& s){s=""; char c; rd(c); do s+=c; while(!isspace(c=Gc())&&~c);}template<typename T,typename... A> inline void rd(T& x,A&... a){rd(x),rd(a...);}template<typename T> inline void wt(T x){if(x<0)Pc('-'),x=-x; static int s[45],t=0; do s[++t]=x%10; while(x/=10);while(t)Pc(s[t--]|48);}inline void wt(char c){Pc(c);}inline void wt(const char* s){while(*s)Pc(*s++);}inline void wt(string s){for(char c:s)Pc(c);}template<typename T,typename... A> inline void wt(T x,A... a){wt(x),Pc(sizeof...(a)?' ':'\n'),(wt(a...),0);}
} using namespace IO;
原文