随笔分类 - 算法模板
摘要:裴蜀定理: 对任意的a,b,有 a*x+b*y = gcd(a,b);当b=0,有 gcd(a,b) = a; 当b≠0: b*y + (a - [a/b]*b)*x = gcd(a,b); b*y + a*x - [a/b]*b*x = gcd(a,b); a*x + b*(y-[a/b]*x)
阅读全文
摘要:能用到拓扑排序的前提: 必须是有向无环图。 如果有环,那么根本不可能形成拓扑排序; 算法流程: 用队列来执行 ,初始化讲所有入度为0的顶点入队。 主要由以下两步循环执行,直到不存在入度为 0 的顶点为止 选择一个入度为 0 的顶点,并将它输出;删除图中从顶点连出的所有边。循环结束, 若输出的顶点数小
阅读全文
摘要:但是第二步求x的编号需要0(n) 的 时间复杂度。 需要进行优化; 压缩路径: 就是运用递归的方法,在找x的祖宗节点的时候,顺便把这一路上的父节点都连到祖宗节点上,那么下一次查询祖宗节点的时候只需0(1)的时间复杂度就可以了。 int find(int x) { if(f[x] != x) f[x]
阅读全文
摘要:这里预处理要用到快速幂求逆元的操作。。。忘记了就复习。 #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N = 1000010, mod = 1e9 + 7;
阅读全文
摘要:快速幂求逆元: #include <iostream> #include <algorithm> using namespace std; typedef long long LL; int n; LL qmi(int a, int b, int p) { LL ans = 1; while(b)
阅读全文
摘要:常用组合数的递推式: 解释: 有a个苹果,从中拿b个苹果; 我们先确定一个苹果a。 然后有两种情况: 一是不包括苹果a,从中拿b个苹果。 二是包含苹果a,再从中拿b-1个苹果。 如此递推。 #include <iostream> using namespace std; const int N =
阅读全文
摘要:基本模型: 找到每一个数左边离他最近的且比他小的(当然也可以反着来); 我们利用一个栈,当栈顶的数比当前的数大(或者等于),那么当 当前的数插入到栈中时,如果下一个数比当前的数(假设已经插入到栈里面了)小,那么当前栈顶的元素就永远用不到了,所以我们可以去除当前栈顶的元素。这样的话,我们这个栈就会呈现
阅读全文
摘要:#include <iostream> #include <algorithm> #include <unordered_map> using namespace std; typedef long long LL; const int mod = 1e9 + 7; int n; int main(
阅读全文
摘要:公式: #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; const int mod = 1e9 + 7; int n; int main() { cin >> n; unor
阅读全文
摘要:#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> get_divisors(int x) { vector<int> ans; for(int i = 1; i <=
阅读全文
摘要:#include <iostream> using namespace std; const int N = 1000010; int primes[N]; bool st[N]; int n, cnt; void get_primes(int x) { for(int i = 2; i <= n;
阅读全文
摘要:我们把从1~n中的数从小到大枚举,在枚举数字i的时候,我们同时要把1~n中所有i的倍数筛掉,这样一直到最后,剩下的数就是1~n中所以的质数。 Code: #include <iostream> using namespace std; const int N = 1000010; int prime
阅读全文
摘要:证明一下循环里面的 i 一定是一个质数:假如 i 是一个合数,那么它一定可以分解成多个质因子相乘的形式,这多个质因子同时也是 a 的质因子且比 i 要小,而比 i 小的数在之前的循环过程中一定是被条件除完了的,所以 i 不可能是合数,只可能是质数 n中最多只含有一个大于sqrt(n)的质因子。证明通
阅读全文
摘要:素数(质数) 是 大于 1 的 数 且 因数只有1 和他本身 #include <iostream> using namespace std; bool is_prime(int x) { if(x < 2) return false; for(int i = 2; i <= x / i; i++)
阅读全文
摘要:类似与快速幂。 由于数据范围很大,我们不能直接用a*b 否则会爆longlong。 我们同样可以采用将b拆分成其对应的二进制形式,然后再用a去乘。 比如说: 4*5 = 4 * (101) = 4*(2^2+2^0) 同样,不管b的二进制最后一位是否为1,a都要乘2,如果是1,结果就乘上a,如果是0
阅读全文
摘要:由于数据比较大,所以我们不可能直接求。 我们可以考虑把拆分成其对应的二进制形式,然后进行求解。 比如说:a = 4, b = 5 那么b的二进制形式就是: 0101 那么4^5 = 4^(2^2+2^0) = 4^2^2 * 4^2^0 由于二进制中相邻两位存在2倍关系,不管b的最后一位是否为1,a
阅读全文
摘要:所以如果是奇数个,那么就是中间那个数,如果是偶数个,那么就是中间两个数任意一个 代码: #include <iostream> #include <algorithm> using namespace std; const int N = 1000010; int q[N]; int main()
阅读全文
摘要:代码: #include <iostream> using namespace std; int main() { int n, ans = 0, m; cin >> n; while(n--) { cin >> m; ans = ans^m; } if(ans) puts("Yes"); else
阅读全文