算法知识点汇总

知识点

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 复制代码
//辗转相减法
相关推荐
聚客AI8 分钟前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v3 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工5 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农6 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了6 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo7 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法