算法知识点汇总

知识点

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 小时前
【AI编程】AI+高德MCP不到10分钟搞定上海三日游
人工智能·算法·程序员
mit6.8241 小时前
[Leetcode] 预处理 | 多叉树bfs | 格雷编码 | static_cast | 矩阵对角线
算法
皮卡蛋炒饭.1 小时前
数据结构—排序
数据结构·算法·排序算法
??tobenewyorker2 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔2 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
众链网络3 小时前
AI进化论08:机器学习的崛起——数据和算法的“二人转”,AI“闷声发大财”
人工智能·算法·机器学习
3 小时前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
飒飒真编程4 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
GeminiGlory4 小时前
算法练习6-大数乘法(高精度乘法)
算法
熬了夜的程序员5 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang