算法知识点汇总

知识点

1. 求二进制中1的个数

cpp 复制代码
int get_count(int x)//返回x的二进制有多少个1
int get_count(int x)
{
    int res = 0;
    while (x)
    {
        res ++ ;
        x -= x & -x;
    }
    return res;
}

2. 建树,和树的DFS

记得初始化头节点

cpp 复制代码
const int N = 1e5 + 10, M = N * 2;
int h[N], e[M], ne[M], idx;

void add(int a, int b)  //如果是无向图,加两条边
{
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int dfs(int u)
{
	state[u] = true;
	for(int  i = h[u]; i != -1; i = ne[i])
	{
		int j = e[i];
		if(!state[j])
			dfs(j);
	}
}

3. 快速幂 O(logk)

用来快速 求出ak mod p的结果

数据范围: 1 <= a, p, k <= 109

cpp 复制代码
//两个十的九次方数相乘会爆int
typedef long long LL;
int qmi(int a, int k, int p)
{
	int res = 1;
	while(k)
	{
		if(k & 1) res = (LL)res * a % p; //要先转型再计算
		k >>= 1;
		a = (LL)a * a % p;
	}
	return res;
}

4. 分解质因数 O(sqrt(n))

cpp 复制代码
void divide(int x)
{
	for(int i = 2; i * i <= x; i++)  //x > 2 * 10^10的范围太大的话,i要定义成LL(9 * 10^19)
		if(x % i == 0)
		{
			int s = 0;
			while(x % i == 0) x /= i, s++;
			cout << i << " " << s << endl;
		}
	//大于根号x的数只能有一个,此时x也是质因子
	if(x > 1) cout << x << " " << 1 << endl; 
	cout << endl;
}		

5. 欧拉函数

cpp 复制代码
int phi(int x)
{
	int res = x;
	for(int i = 2; i * i <= n; i++)
		if(x % i == 0)
		{
			while(x % i == 0) x /= i;
			res = res / i * (i - 1);
		}
	if(x > 1) res = res / x * ( x - 1 );
	return res;
}

6. 最大公约数 O(n(log(n))

cpp 复制代码
//辗转相除法
int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}
cpp 复制代码
//辗转相减法
相关推荐
地平线开发者1 天前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮1 天前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者1 天前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考1 天前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx1 天前
CART决策树基本原理
算法·机器学习
Wect1 天前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱1 天前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
Gorway2 天前
解析残差网络 (ResNet)
算法
拖拉斯旋风2 天前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect2 天前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript