-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm.h
98 lines (83 loc) · 1.94 KB
/
algorithm.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <bits/stdc++.h>
using namespace std;
template<class T>
T gcd(T a, T b)
{
if (a == 0) return b;
else if (b == 0) return a;
if (b > a) swap(a, b); // assume a >= b
T ret = b;
while (a % b != 0) {
ret = a % b;
a = b;
b = ret;
}
return ret;
}
long long modPow(long long x, long long n, const long long MOD)
{
long long ans = 1;
while (n != 0) {
if (n & 1) ans = ans * x % MOD;
x = x * x % MOD;
n = n >> 1;
}
return ans;
}
long long modPerm(const long long n, const long long k, const long long MOD)
{
long long per = 1;
for (long long i = 0; i < k; ++i) {
per *= (n - i);
per %= MOD;
}
return per;
}
long long modFact(const long long n, const long long MOD)
{
long long fac = 1;
for (long long i = 1; i <= n; ++i) {
fac *= i;
fac %= MOD;
}
return fac;
}
long long modComb(const long long n, long long r, const long long MOD)
{
if (n < r || n < 0) return 0;
if (r * 2 > n) r = n - r;
return ((modFact(n, MOD) * modPow(modFact(r, MOD), MOD - 2, MOD) % MOD)
* modPow(modFact(n - r, MOD), MOD - 2, MOD)) % MOD;
}
template<typename type>
class UnionFindTree
{
private:
vector<type> parent;
vector<type> rank;
public:
UnionFindTree(type size) {
parent.resize(size);
rank.resize(size, 0);
for (type i = 0; i < size; ++i) {
parent[i] = i;
}
}
type findRoot(type x) {
if (parent[x] == x) return x;
else return parent[x] = findRoot(parent[x]);
}
void uniteTwoGroups(type x, type y) {
x = findRoot(x);
y = findRoot(y);
if (x == y) return;
if (rank[x] < rank[y]) parent[x] = y;
else {
parent[y] = x;
if (rank[x] == rank[y]) ++rank[x];
}
}
bool areSameGroups(type x, type y) {
return findRoot(x) == findRoot(y);
}
};