跳到正文

算法·理论

trick

dk_qwq约 17 分钟
原文

这是 2025年12月9日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2023年10月12日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 17 分钟
获赞
2

版本

  1. v5当前
  2. v4
  3. v3
  4. v2
更早的 1 个版本
  1. v1
C++
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
namespace INPUT{
    char buf[1<<20],*p1,*p2;
    #define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
}
using namespace INPUT;
template<typename T>
inline T read(){
    T x=0,p=1;
    char ch=gc();
    for(;ch<'0'||ch>'9';ch=gc())
        if(ch=='-') p=-1;
    for(;ch>='0'&&ch<='9';ch=gc())
        x=(x<<3)+(x<<1)+(ch^48);
    return x*p;
}
void solve(){
    
}
int main(){
    freopen("A.in","r",stdin);
    freopen("A.out","w",stdout);
    int T=read<int>();
    while(T--) solve();
}
Python
# check.py
inFile = open("A.in", "r")
outFile = open("A.out", "r")

n = int(inFile.readline())
a = [0] * n
b = [0] * n
for i in range(0, n):
    a[i], b[i] = map(int, inFile.readline().split())

ans = int(outFile.readline())

last = [0] * n
group = list(map(int, outFile.readline().split()))

flag = False
for i in range(0, n):
    w = group[i]
    if last[w] > b[i]:
        open("A.ans", "w").write("False")
        flag = True
        break
    last[w] = b[i]

if flag == False:
    open("A.ans", "w").write("True")
Python
import random

random.randint(l, r)
random.choice(list)
random.sample(list, k)
random.shuffle(list)

f = open("data.in", "w")

with open("data.in", "w") as f:
    f.write("...\n")
    print("...", file = f)
Python
import random

def gen(n, m):
    print(n, m)
    for _ in range(n):
        print(random.randint(1, 1000), end=' ')
    print()

if __name__ == "__main__":
    gen(10, 5)
Python
p = list(range(1, n+1)) #生成 permutation
random.shuffle(p)

对于 G=(V,E)G = (V, E) 有最小生成树 T=(V,E′)T = (V, E') ,那么 G′=(V∪Vnew,E∪Vnew)G' = (V \cup V_{new}, E \cup V_{new}) 的最小生成树的边集 ET′∩(E∖E′)=∅E_{T'} \cap (E \setminus E') = \empty ,也就是说加入新点可在原最小生成树上做

python中可以直接使用 pow(x, k, mod) ,不需要导入任何库

C++
struct DSU { // 带权并查集
  std::vector<size_t> pa, size, dist;

  explicit DSU(size_t size_) : pa(size_), size(size_, 1), dist(size_) {
    std::iota(pa.begin(), pa.end(), 0);
  }

  size_t find(size_t x) {
    if (pa[x] == x) return x;
    size_t y = find(pa[x]);
    (dist[x] += dist[pa[x]]) %= M;
    return pa[x] = y;
  }

  bool unite(size_t x, size_t y, int d) { // a[x] = a[y] + d;
    find(x), find(y);
    (d += M - dist[y]) %= M;
    (d += dist[x]) %= M;
    x = pa[x], y = pa[y];
    if (x == y) return d == 0;
    if (size[x] < size[y]) {
      std::swap(x, y);
      d = (M - d) % M;
    }
    pa[y] = x;
    size[x] += size[y];
    dist[y] = d;
    return true;
  }

  int check(size_t x, size_t y) { // a[x] - a[y]
    find(x), find(y);
    if (pa[x] != pa[y]) return -1;
    return (dist[y] - dist[x] + M) % M;
  }
};
C++
struct fenwick{ //二维树状数组
  void add(int x, int y, int v) {
    for (int i = x; i <= n; i += lowbit(i))
      for (int j = y; j <= m; j += lowbit(j)) c[i][j] += v;
  }
};

#define debug(a) cout<<#a<<"="<<a<<endl;

C++
std::map<int, std::string> mp = {{1, "a"}, {2, "b"}, {3, "c"}}; // 反向迭代map
for (auto&& [k, v] : std::views::reverse(std::views::all(map))) { ... }
for (auto&& [k, v] : mp | rv::all | rv::reverse)
    std::cout << k << " " << v << "\n";

对于长度分别为 l1,l2,…,lml_1, l_2, \dots, l_m 的 mm 根小木棍,这 mm 根小木棍能拼成一个多边形当且仅当 m≥3m \geq 3 且 ∑i=1mli>2×max⁡i=1mli\sum_{i=1}^{m} l_i > 2 \times \max_{i=1}^{m} l_i。

Measure-Command {A.exe} powershell 测程序运行时间

C++
for (auto i : views::iota(1, n + 1)) {}

O(1)O(1) 计算区间2进制第 kk 位为 11 的整数个数

Python
def count_up_to(x, k):
    """计算 [0, x] 中二进制第 k 位为 1 的整数个数"""
    if x < 0:
        return 0
    T = 1 << (k + 1)      # 周期长度 2^(k+1)
    L = 1 << k            # 每个周期中 1 的数量 2^k
    full_cycles = (x + 1) // T
    remainder = (x + 1) % T
    return full_cycles * L + max(0, remainder - L)

def query_range(l, r, k):
    """查询 [l, r] 中二进制第 k 位为 1 的整数个数"""
    return count_up_to(r, k) - count_up_to(l - 1, k)

# 示例测试
print(query_range(0, 7, 1))  # 在 0..7 中第 1 位为 1 的个数
print(query_range(1, 1e18, 50))  # 大数计算
C++
// ranges::partition_point的使用
// check 在 range 内需要满足单调性, 先 true 后 false,所以有时可能得反转 check 返回值,需结合题目。
int n = 5;
std::vector<int> v{1, 3, 4, 2, 6};
auto odd = [&](int x) {
    return x % 2 == 1;
};

auto p = std::ranges::partition_point(v, odd);
std::cout << *p << '\n';
// p 是 v[2] 的迭代器, output v[2] 的内容 4
// 需注意这里如果 v 全是奇数,则会返回 v.end()

auto check = [&](int idx) {
    return v[idx] % 2 == 1;
};
int bound = *std::ranges::partition_point(std::ranges::iota_view(0, n), check);
std::cout << bound << '\n';
// bound = 2,对应第一个下标
// 注意 iota_view 是一个 O(1) 的虚拟范围, 所以 iota_view(0, 10^9) 是 ok 的,可以用来二分答案
// 由于 iota_view 区间是左闭右开, 使用时最好传入 iota_view(l, r + 1)
// 二分答案再也不用担心 l r 调整错
C++
#include <iostream>
#include <random>
using namespace std;
// 用随机设备作为种子,保证每次运行不一样
random_device rd;       
mt19937 gen(rd());      

// 或者用固定种子,保证结果可复现
mt19937 gen2(42);       
uniform_int_distribution<int> dist(1, 6); // [1,6] 区间
cout << dist(gen) << endl;  // 模拟掷骰子

C++
struct PairHash {
    size_t operator()(const std::pair<int,int>& p) const noexcept {
        return std::hash<long long>()(((long long)p.first << 32) ^ p.second);
    }
};
std::unordered_map<std::pair<int, int>, ll, PairHash> count;

注意自己实现的hashMap性能不行,尽量不要用,用std::unordered_map<int, std::unordered_map<int, ll> > ;更好


w∈[1,B−1],r=⌈B2W⌉⇒r is diff w \in [1, B - 1], r = \lceil {\frac {B^2} {W}} \rceil \Rightarrow \text {r is diff}
类型模数 (mod)常用基数 (base)说明
单模数常用1,000,000,007 (1e9+7)131, 137, 911382323经典,OJ 通用
单模数常用1,000,000,009 (1e9+9)131, 233, 911382323常和 1e9+7 搭配
单模数常用998,244,35361, 107, 131, 233NTT 质数,代码里常见
双模数组合(1e9+7, 1e9+9)(131, 137)最经典的双模哈希
双模数组合(998244353, 1e9+7)(233, 911382323)抗碰撞性更高
64位自然溢出2^64 (unsigned long long)随机奇数 ~ 1e5..1e9无需取模,溢出即模 2^64

首先,我们将所有位于 任意一条从 11 到 nn 的路径上的边的集合记作 AA。

接着,找出图中的所有 桥(割边),将这些边的集合记作 BB。

然后,任选一条从 11 到 nn 的简单路径,将路径上的边的集合记作 PP。

那么:B∩P=A B \cap P = A


若存在函数 f(x) 使得 ∀x∈Z,f(x)∈Z\text{若存在函数 }f(x) \text{ 使得 } \forall x \in Z , f(x) \in Z 则有 ⌈f(x)⌉=⌈f(⌈x⌉)⌉,⌊f(x)⌋=⌊f(⌊x⌋)⌋\text{则有 } {\lceil f(x) \rceil}={\lceil f(\lceil x \rceil) \rceil},{\lfloor f(x) \rfloor}={\lfloor f(\lfloor x \rfloor) \rfloor}

f(i)=preA[i]+preB[z−i]f(i)=preA[i]+preB[z−i] 是单峰的(A[i],B[i]>0A[i],B[i] > 0 )


n=2k(k≥2)n=2^k ( k \geq 2 ) 的时候 1⊕⋯⊕(n−1)=01 \oplus \dots \oplus (n-1) = 0

  • 如果 n(mod4)=0n \pmod 4 = 0,则 1⊕⋯⊕n=n1 \oplus \dots \oplus n = n。
  • 如果 n(mod4)=1n \pmod 4 = 1,则 1⊕⋯⊕n=11 \oplus \dots \oplus n = 1。
  • 如果 n(mod4)=2n \pmod 4 = 2,则 1⊕⋯⊕n=n+11 \oplus \dots \oplus n = n+1。
  • 如果 n(mod4)=3n \pmod 4 = 3,则 1⊕⋯⊕n=01 \oplus \dots \oplus n = 0。

O(∑d=1m1d)=O(logm) O ( \sum_{d = 1} ^m \frac {1} {d} ) = O (log m)
  1. 清空(queue等)
C++
template<typename T>
void clear(T& v){T().swap(v);}
  1. 可重集multiset的使用
C++
multiset::find(val)//查值
multiset::erase(val)//删值
multiset::erase(it)//删迭代器
multiset::erase(find(val))//删点
(*multiset::begin())//min_val
(*prev(multiset::end()))//max_val
C++
pair<ll,ll> solve(vector<ll>& a,ll w){//一段序列中匹配一对数对和中大于w的
	for(auto v:a) s.insert(v);
	ll res=0,Max=0;
	while(s.size()>=2){
		auto l=s.begin();
		auto it=s.lower_bound(w-(*l));
		if(l==it) it++;
		if(it==s.end()) Max=max(Max,(*l)),s.erase(l);
		else res++,s.erase(l),s.erase(it);
	}
	while(!s.empty())
		Max=max(Max,*(s.begin())),s.erase(s.begin());
	return MP(res,Max);//返回匹配值与剩余最大值
}
  1. 加法操作和乘法操作复合的pushdown
C++
void pushMu(int x,ll v){
	if(!x) return ;
	LazyS[x]*=v;
	LazyMu[x]*=v;
	val[x]*=v;
}
void pushS(int x,ll v){
	if(!x) return ;
	if(LazyMu[x]!=1){
		pushMu(lc[x],LazyMu[x]),pushMu(rc[x],LazyMu[x]);
		LazyMu[x]=1;
	}
	LazyS[x]+=v;
	val[x]+=v;
}
void pushdown(int x){//先乘上在加上
	if(LazyMu[x]!=1){
		pushMu(lc[x],LazyMu[x]),pushMu(rc[x],LazyMu[x]);
		LazyMu[x]=1;
	}
	if(LazyS[x]){
		pushS(lc[x],LazyS[x]),pushS(rc[x],LazyS[x]);
		LazyS[x]=0;
	}
}
  1. prev
C++
template< class BidirIt >
BidirIt prev( BidirIt it, typename std::iterator_traits<BidirIt>::difference_type n = 1 );

Return the n_th predecessor (or -nth successor if n is negative) of iterator it.
  1. 生成给定序列的下一个字典序排列 O(n)O(n)
C++
#include <algorithm>
bool next_permutation(iterator start, iterator end);

template< class BidirIt, class Compare >bool next_permutation( BidirIt first, BidirIt last, Compare comp );