13 行代码C++工具函数
方向数组
二维数组枚举、BFS/DFS 常用的方向数组
// 上下左右四方向
int dx4[] = {-1, 1, 0, 0};
int dy4[] = {0, 0, -1, 1};
// 上下左右、左上右上、左下右下八方向
int dx8[] = {-1, 1, 0, 0, -1, -1, 1, 1};
int dy8[] = {0, 0, -1, 1, -1, 1, -1, 1};#方向数组#枚举
二维数组枚举、BFS/DFS 常用的方向数组
// 上下左右四方向
int dx4[] = {-1, 1, 0, 0};
int dy4[] = {0, 0, -1, 1};
// 上下左右、左上右上、左下右下八方向
int dx8[] = {-1, 1, 0, 0, -1, -1, 1, 1};
int dy8[] = {0, 0, -1, 1, -1, 1, -1, 1};竞赛中,应对整数向上取整的简单方法
// ceil((double)n / a); 限制较多
(n + a - 1) / a;常常和最大公约数配合使用
int lcm(int a, int b) {
return a / gcd(a, b) * b; // 先除后乘,防止溢出
}关闭 C++ 与 C 的输入输出同步,提高 cin/cout 速度
ios::sync_with_stdio(false);
cin.tie(nullptr);使用递归实现欧几里得/辗转相除法求最大公约数
int gcd(int a, int b) {
if (a % b == 0) return b;
return gcd(b, a % b);
}使用循环实现欧几里得/辗转相除法求最大公约数
int gcd(int a, int b) {
while (a % b) {
int t = a % b;
a = b;
b = t;
}