text
stringlengths 2
104M
| meta
dict |
---|---|
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/queries/WaveletMatrixTreeAggregation.h"
#include "../../../../Content/C++/graph/queries/WaveletMatrixHeavyLightDecomposition.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
#include "../../../../Content/C++/datastructures/trees/fenwicktrees/BitFenwickTree.h"
using namespace std;
struct R1 {
using Data = int;
using Lazy = int;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) { return l + r; }
static Data invData(const Data &v) { return -v; }
BitFenwickTree FT;
R1(const vector<Data> &A) : FT(A.size()) {
for (int i = 0; i < int(A.size()); i++) FT.set(i, A[i]);
FT.build();
}
void update(int i, const Lazy &val) { FT.update(i, val); }
Data query(int r) { return FT.query(r); }
};
struct R2 {
using Data = int;
using Lazy = int;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) { return l + r; }
BitFenwickTree FT;
R2(const vector<Data> &A) : FT(A.size()) {
for (int i = 0; i < int(A.size()); i++) FT.set(i, A[i]);
FT.build();
}
void update(int i, const Lazy &val) { FT.update(i, val); }
Data query(int l, int r) { return FT.query(l, r); }
};
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4, MAXA = 100;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int V = rng() % 101;
vector<int> A(V, 0);
for (int v = 1; v < V; v++) A[v] = rng() % MAXA;
vector<int> X(V, 0);
for (int v = 1; v < V; v++) X[v] = rng() % 2;
StaticGraph G(V);
for (int v = 1; v < V; v++) G.addBiEdge(rng() % v, v);
G.build();
WaveletMatrixTreeAggregation<int, R1, true> wm(G, A, X);
WaveletMatrixHLD<int, R2, true> hld(G, A, X);
int Q = V <= 1 ? 0 : rng() % 101;
vector<int> par(V), dep(V);
function<void(int, int, int)> dfs = [&] (int v, int prev, int d) {
par[v] = prev;
dep[v] = d;
for (int w : G[v]) if (w != prev) dfs(w, v, d + 1);
};
if (V > 0) dfs(0, -1, 0);
auto getPath = [&] (int v, int w) {
vector<int> ret, ret2;
while (v != w) {
if (dep[v] > dep[w]) {
ret.push_back(v);
v = par[v];
} else {
ret2.push_back(w);
w = par[w];
}
}
reverse(ret2.begin(), ret2.end());
ret.insert(ret.end(), ret2.begin(), ret2.end());
return ret;
};
vector<int> ans0, ans1, ans2;
for (int i = 0; i < Q; i++) {
int t = rng() % 3;
if (t == 0) {
int v;
do {
v = rng() % V;
} while (v == 0);
wm.update(v, X[v] ^= 1);
hld.update(v, X[v]);
} else if (t == 1) {
int v = rng() % V, w;
do {
w = rng() % V;
} while (v == w);
int a = rng() % MAXA, b = rng() % MAXA;
if (a > b) swap(a, b);
int sm = 0;
for (int x : getPath(v, w)) if (a <= A[x] && A[x] <= b) sm += X[x];
ans0.push_back(sm);
ans1.push_back(wm.query(v, w, a, b));
ans2.push_back(hld.query(v, w, a, b));
} else {
int v = rng() % V, w;
do {
w = rng() % V;
} while (v == w);
int k = rng() % ((wm.query(v, v, MAXA) + 1) * 2);
vector<int> C;
for (int x : getPath(v, w)) if (X[x]) C.push_back(A[x]);
sort(C.begin(), C.end());
if (k == 0) ans0.push_back(*min_element(A.begin(), A.end()));
else if (k - 1 < int(C.size())) ans0.push_back(C[k - 1]);
else ans0.push_back(INT_MAX);
pair<bool, int *> p = wm.bsearch(v, w, [&] (int agg) {
return agg >= k;
});
ans1.push_back(p.first ? *p.second : INT_MAX);
p = hld.bsearch(v, w, [&] (int agg) {
return agg >= k;
});
ans2.push_back(p.first ? *p.second : INT_MAX);
}
}
assert(ans0 == ans1);
assert(ans0 == ans2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Values on Edges) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4, MAXA = 100;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int V = rng() % 101;
vector<int> A(V, 0);
for (int v = 0; v < V; v++) A[v] = rng() % MAXA;
vector<int> X(V, 0);
for (int v = 0; v < V; v++) X[v] = rng() % 2;
StaticGraph G(V);
for (int v = 1; v < V; v++) G.addBiEdge(rng() % v, v);
G.build();
WaveletMatrixTreeAggregation<int, R1, false> wm(G, A, X);
WaveletMatrixHLD<int, R2, false> hld(G, A, X);
int Q = V == 0 ? 0 : rng() % 101;
vector<int> par(V), dep(V);
function<void(int, int, int)> dfs = [&] (int v, int prev, int d) {
par[v] = prev;
dep[v] = d;
for (int w : G[v]) if (w != prev) dfs(w, v, d + 1);
};
if (V > 0) dfs(0, -1, 0);
auto getPath = [&] (int v, int w) {
vector<int> ret, ret2;
while (v != w) {
if (dep[v] > dep[w]) {
ret.push_back(v);
v = par[v];
} else {
ret2.push_back(w);
w = par[w];
}
}
ret.push_back(v);
reverse(ret2.begin(), ret2.end());
ret.insert(ret.end(), ret2.begin(), ret2.end());
return ret;
};
vector<int> ans0, ans1, ans2;
for (int i = 0; i < Q; i++) {
int t = rng() % 3;
if (t == 0) {
int v = rng() % V;
wm.update(v, X[v] ^= 1);
hld.update(v, X[v]);
} else if (t == 1) {
int v = rng() % V, w = rng() % V;
int a = rng() % MAXA, b = rng() % MAXA;
if (a > b) swap(a, b);
int sm = 0;
for (int x : getPath(v, w)) if (a <= A[x] && A[x] <= b) sm += X[x];
ans0.push_back(sm);
ans1.push_back(wm.query(v, w, a, b));
ans2.push_back(hld.query(v, w, a, b));
} else {
int v = rng() % V, w = rng() % V;
int k = rng() % ((wm.query(v, v, MAXA) + 1) * 2);
vector<int> C;
for (int x : getPath(v, w)) if (X[x]) C.push_back(A[x]);
sort(C.begin(), C.end());
if (k == 0) ans0.push_back(*min_element(A.begin(), A.end()));
else if (k - 1 < int(C.size())) ans0.push_back(C[k - 1]);
else ans0.push_back(INT_MAX);
pair<bool, int *> p = wm.bsearch(v, w, [&] (int agg) {
return agg >= k;
});
ans1.push_back(p.first ? *p.second : INT_MAX);
p = hld.bsearch(v, w, [&] (int agg) {
return agg >= k;
});
ans2.push_back(p.first ? *p.second : INT_MAX);
}
}
assert(ans0 == ans1);
assert(ans0 == ans2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Values on Vertices) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/components/StronglyConnectedComponents.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
StaticGraph G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int c = rng() % 100;
int v = rng() % (V / 100) + (V / 100) * c, w = rng() % (V / 100) + (V / 100) * c;
G.addDiEdge(v, w);
}
G.build();
const auto start_time = chrono::system_clock::now();
vector<pair<int, int>> condensationEdges;
SCC scc(G, condensationEdges);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + scc.id[v];
sort(condensationEdges.begin(), condensationEdges.end());
for (auto &&e : condensationEdges) {
checkSum = 31 * checkSum + e.first;
checkSum = 31 * checkSum + e.second;
}
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/components/BiconnectedComponents.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
StaticGraph G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int c = rng() % 2;
int v = rng() % (V / 2) + (V / 2) * c, w = rng() % (V / 2) + (V / 2) * c;
G.addBiEdge(v, w);
}
G.build();
const auto start_time = chrono::system_clock::now();
vector<pair<int, int>> blockCutForestEdges;
BCC bcc(G, blockCutForestEdges);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) {
checkSum = 31 * checkSum + v;
for (int id : bcc.ids[v]) checkSum = 31 * checkSum + id;
}
sort(blockCutForestEdges.begin(), blockCutForestEdges.end());
for (auto &&e : blockCutForestEdges) {
checkSum = 31 * checkSum + e.first;
checkSum = 31 * checkSum + e.second;
}
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/components/Bridges.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
StaticGraph G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int c = rng() % 2;
int v = rng() % (V / 2) + (V / 2) * c, w = rng() % (V / 2) + (V / 2) * c;
G.addBiEdge(v, w);
}
G.build();
const auto start_time = chrono::system_clock::now();
Bridges bridges(G);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + bridges.id[v];
sort(bridges.bridges.begin(), bridges.bridges.end());
for (auto &&e : bridges.bridges) {
checkSum = 31 * checkSum + e.first;
checkSum = 31 * checkSum + e.second;
}
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/components/ConnectedComponents.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
CC cc(V);
for (int i = 0; i < E; i++) {
int c = rng() % 100;
int v = rng() % (V / 100) + (V / 100) * c, w = rng() % (V / 100) + (V / 100) * c;
cc.addEdge(v, w);
}
cc.assign();
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + cc.id[v];
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/minimumspanningtree/ClassicalPrimMST.h"
#include "../../../../Content/C++/graph/minimumspanningtree/BoruvkaMST.h"
#include "../../../../Content/C++/graph/minimumspanningtree/KruskalMST.h"
#include "../../../../Content/C++/graph/minimumspanningtree/PrimMST.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 1e4, E = 5e6;
vector<KruskalMST<long long>::Edge> edges;
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
edges.emplace_back(v, w, weight);
}
const auto start_time = chrono::system_clock::now();
KruskalMST<long long> mst(V, move(edges));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Kruskal) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int V = 1e6, E = 5e6;
vector<KruskalMST<long long>::Edge> edges;
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
edges.emplace_back(v, w, weight);
}
const auto start_time = chrono::system_clock::now();
KruskalMST<long long> mst(V, move(edges));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Kruskal) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test3() {
mt19937_64 rng(0);
int V = 1e4, E = 5e6;
vector<BoruvkaMST<long long>::Edge> edges;
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
edges.emplace_back(v, w, weight);
}
const auto start_time = chrono::system_clock::now();
BoruvkaMST<long long> mst(V, move(edges));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Boruvka) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test4() {
mt19937_64 rng(0);
int V = 1e6, E = 5e6;
vector<BoruvkaMST<long long>::Edge> edges;
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
edges.emplace_back(v, w, weight);
}
const auto start_time = chrono::system_clock::now();
BoruvkaMST<long long> mst(V, move(edges));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Boruvka) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test5() {
mt19937_64 rng(0);
int V = 1e4, E = 5e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
G.addBiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
PrimMST<long long> mst(move(G));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Prim) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test6() {
mt19937_64 rng(0);
int V = 1e6, E = 5e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
G.addBiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
PrimMST<long long> mst(move(G));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Prim) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
void test7() {
mt19937_64 rng(0);
int V = 1e4, E = 5e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % (long long)(1e9) + 1;
G.addBiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
ClassicalPrimMST<long long> mst(move(G));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 7 (Classical Prim) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = mst.mstWeight;
for (auto &&e : mst.mstEdges) if (get<0>(e) > get<1>(e)) swap(get<0>(e), get<1>(e));
sort(mst.mstEdges.begin(), mst.mstEdges.end());
for (auto &&e : mst.mstEdges) {
checkSum = 31 * checkSum + get<0>(e);
checkSum = 31 * checkSum + get<1>(e);
checkSum = 31 * checkSum + get<2>(e);
}
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/bipartite/Bipartite.h"
#include "../../../../Content/C++/graph/bipartite/IncrementalBipartite.h"
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
StaticGraph G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
G.addBiEdge(v, w);
}
G.build();
const auto start_time = chrono::system_clock::now();
Bipartite bp(G);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Bipartite) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = bp.bipartite;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
IncrementalBipartite ibp(V);
const auto start_time = chrono::system_clock::now();
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
ibp.addEdge(v, w);
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Incremental Bipartite) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = ibp.bipartiteGraph;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
StaticGraph G(V);
G.reserveDiEdges(E * 2);
for (int i = 0; i < E; i++) {
int v = rng() % (V / 2) * 2, w = rng() % (V / 2) * 2 + 1;
G.addBiEdge(v, w);
}
G.build();
const auto start_time = chrono::system_clock::now();
Bipartite bp(G);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Bipartite) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = bp.bipartite;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
mt19937_64 rng(0);
int V = 2e6, E = 4e6;
IncrementalBipartite ibp(V);
const auto start_time = chrono::system_clock::now();
for (int i = 0; i < E; i++) {
int v = rng() % (V / 2) * 2, w = rng() % (V / 2) * 2 + 1;
ibp.addEdge(v, w);
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Incremental Bipartite) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = ibp.bipartiteGraph;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/shortestpaths/ShortestHamiltonianCycle.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int V = rng() % 8, E = V == 0 ? 0 : rng() % (V * V);
vector<vector<long long>> matrix(V, vector<long long>(V, LLONG_MAX));
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = int(rng() % (int(2e9) + 1)) - int(1e9);
matrix[v][w] = min(matrix[v][w], weight);
}
ShortestHamiltonianCycle<long long> shp(matrix);
vector<int> P(V);
iota(P.begin(), P.end(), 0);
long long mn = LLONG_MAX;
do {
long long dist = 0;
bool valid = true;
for (int i = 0; valid && i < V; i++) {
if (matrix[P[i]][P[(i + 1) % V]] == LLONG_MAX) valid = false;
dist += matrix[P[i]][P[(i + 1) % V]];
}
if (valid) mn = min(mn, dist);
} while (next_permutation(P.begin(), P.end()));
assert(mn == shp.shortestCycleDist);
if (shp.shortestCycleDist != LLONG_MAX) {
long long checkDist = 0;
for (int i = 0; i < V; i++) checkDist += matrix[shp.ord[i]][shp.ord[(i + 1) % V]];
assert(shp.shortestCycleDist == checkDist);
}
checkSum = 31 * checkSum + shp.shortestCycleDist;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/shortestpaths/ShortestHamiltonianPath.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int V = rng() % 8, E = V == 0 ? 0 : rng() % (V * V);
vector<vector<long long>> matrix(V, vector<long long>(V, LLONG_MAX));
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = int(rng() % (int(2e9) + 1)) - int(1e9);
matrix[v][w] = min(matrix[v][w], weight);
}
ShortestHamiltonianPath<long long> shp(matrix);
vector<int> P(V);
iota(P.begin(), P.end(), 0);
long long mn = LLONG_MAX;
do {
long long dist = 0;
bool valid = true;
for (int i = 0; valid && i < V - 1; i++) {
if (matrix[P[i]][P[i + 1]] == LLONG_MAX) valid = false;
dist += matrix[P[i]][P[i + 1]];
}
if (valid) mn = min(mn, dist);
} while (next_permutation(P.begin(), P.end()));
assert(mn == shp.shortestPathDist);
if (shp.shortestPathDist != LLONG_MAX) {
long long checkDist = 0;
for (int i = 0; i < V - 1; i++) checkDist += matrix[shp.ord[i]][shp.ord[i + 1]];
assert(shp.shortestPathDist == checkDist);
}
checkSum = 31 * checkSum + shp.shortestPathDist;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/representations/StaticGraph.h"
#include "../../../../Content/C++/graph/shortestpaths/BellmanFordSSSP.h"
#include "../../../../Content/C++/graph/shortestpaths/ClassicalDijkstraSSSP.h"
#include "../../../../Content/C++/graph/shortestpaths/DijkstraSSSP.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 1e4, E = 4e4;
vector<tuple<int, int, long long>> edges;
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
edges.emplace_back(v, w, weight);
}
const auto start_time = chrono::system_clock::now();
BellmanFordSSSP<long long> sssp(V, edges, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Bellman Ford) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int V = 1e4, E = 4e4;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
G.addDiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
ClassicalDijkstraSSSP<long long> sssp(G, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Classical Dijkstra) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
void test3() {
mt19937_64 rng(0);
int V = 1e4, E = 4e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
G.addDiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
ClassicalDijkstraSSSP<long long> sssp(G, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Classical Dijkstra) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
void test4() {
mt19937_64 rng(0);
int V = 1e4, E = 4e4;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
G.addDiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
DijkstraSSSP<long long> sssp(G, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Dijkstra with PQ) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
void test5() {
mt19937_64 rng(0);
int V = 1e4, E = 4e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
G.addDiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
DijkstraSSSP<long long> sssp(G, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Dijkstra with PQ) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
void test6() {
mt19937_64 rng(0);
int V = 1e6, E = 4e6;
StaticWeightedGraph<long long> G(V);
G.reserveDiEdges(E);
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
G.addDiEdge(v, w, weight);
}
G.build();
const auto start_time = chrono::system_clock::now();
DijkstraSSSP<long long> sssp(G, 0);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Dijkstra with PQ) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) checkSum = 31 * checkSum + sssp.dist[v];
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/shortestpaths/FloydWarshallAPSP.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int V = 500, E = 2e4;
vector<vector<long long>> matrix(V, vector<long long>(V, LLONG_MAX));
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = rng() % int(1e9) + 1;
matrix[v][w] = min(matrix[v][w], weight);
}
const auto start_time = chrono::system_clock::now();
FloydWarshallAPSP<long long> apsp(matrix);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Floyd Warshall) Passed" << endl;
cout << " V: " << V << endl;
cout << " E: " << E << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int v = 0; v < V; v++) for (int w = 0; w < V; w++) checkSum = 31 * checkSum + apsp.dist[v][w];
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/graph/shortestpaths/FloydWarshallAPSP.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int V = rng() % 11, E = V == 0 ? 0 : rng() % (V * V);
vector<vector<long long>> matrix(V, vector<long long>(V, LLONG_MAX));
for (int i = 0; i < E; i++) {
int v = rng() % V, w = rng() % V;
long long weight = int(rng() % (int(2e9) + 1)) - int(1e9);
matrix[v][w] = min(matrix[v][w], weight);
}
FloydWarshallAPSP<long long> apsp(matrix);
for (int v = 0; v < V; v++) for (int w = 0; w < V; w++) {
if (abs(apsp.dist[v][w]) != apsp.INF) {
vector<tuple<int, int, long long>> path = apsp.getPath(v, w);
long long sm = 0;
for (auto &&e : path) {
sm += get<2>(e);
assert(get<2>(e) == matrix[get<0>(e)][get<1>(e)]);
}
assert(sm == apsp.dist[v][w]);
}
checkSum = 31 * checkSum + apsp.dist[v][w];
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/unionfind/UnionFind.h"
#include "../../../../Content/C++/geometry/2d/Point.h"
#include "../../../../Content/C++/geometry/2d/Line.h"
#include "../../../../Content/C++/geometry/2d/Polygon.h"
#include "../../../../Content/C++/geometry/2d/PolygonTriangulation.h"
#include "../../../../Content/C++/graph/representations/AdjacencyListGraph.h"
using namespace std;
vector<pt> generatePolygon(int N, mt19937_64 &rng, bool grid) {
vector<pt> P(N);
assert(N >= 3);
set<pt> seen;
if (grid) {
uniform_int_distribution<int> dis(0, 10);
while (true) {
for (auto &&p : P) {
do {
p.x = dis(rng);
p.y = dis(rng);
} while (seen.count(p));
seen.insert(p);
}
sort(P.begin(), P.end());
T sm = 0;
for (int i = 0; i < N - 1; i++) sm += dist(P[i], P[i + 1]);
if (!eq(sm, dist(P[0], P[N - 1]))) break;
}
} else {
uniform_real_distribution<T> dis(0, 10);
while (true) {
for (auto &&p : P) {
do {
p.x = dis(rng);
p.y = dis(rng);
} while (seen.count(p));
seen.insert(p);
}
sort(P.begin(), P.end());
T sm = 0;
for (int i = 0; i < N - 1; i++) sm += dist(P[i], P[i + 1]);
if (!eq(sm, dist(P[0], P[N - 1]))) break;
}
}
vector<pair<int, int>> edges;
for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) edges.emplace_back(i, j);
sort(edges.begin(), edges.end(), [&] (const pair<int, int> &a, const pair<int, int> &b) {
return dist(P[a.first], P[a.second]) < dist(P[b.first], P[b.second]);
});
UnionFind uf(N);
AdjacencyListGraph G(N);
for (auto &&e : edges) if (uf.join(e.first, e.second)) G.addBiEdge(e.first, e.second);
for (int v = 0; v < N; v++) shuffle(G[v].begin(), G[v].end(), rng);
vector<pt> ret;
function<void(int, int)> dfs = [&] (int v, int prev) {
ret.push_back(P[v]);
for (int w : G[v]) if (w != prev) dfs(w, v);
};
dfs(0, -1);
bool done = false;
while (!done) {
done = true;
for (int i = 0; i < N; i++) for (int j = i + 2; j < N; j++) if (mod(j + 1, N) != i) {
if (segSegIntersects(ret[i], ret[mod(i + 1, N)], ret[j], ret[mod(j + 1, N)])) {
reverse(ret.begin() + i + 1, ret.begin() + j + 1);
done = false;
}
}
}
return ret;
}
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
long long checkSum = 0;
uniform_int_distribution<int> dis(3, 30);
for (int ti = 0; ti < TESTCASES; ti++) {
vector<pt> poly = generatePolygon(dis(rng), rng, false);
if (isCcwPolygon(poly) == -1) reverse(poly.begin(), poly.end());
T a2 = getArea2(poly), sm = 0;
auto tris = polygonTriangulation(poly);
assert(int(tris.size()) == int(poly.size()) - 2);
for (auto &&t : tris) {
T ta2 = area2(t[0], t[1], t[2]);
assert(lt(0, ta2));
sm += ta2;
}
assert(eq(a2, sm));
checkSum += a2;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Random) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
long long checkSum = 0;
uniform_int_distribution<int> dis(3, 30);
for (int ti = 0; ti < TESTCASES; ti++) {
vector<pt> poly = generatePolygon(dis(rng), rng, true);
if (isCcwPolygon(poly) == -1) reverse(poly.begin(), poly.end());
T a2 = getArea2(poly), sm = 0;
auto tris = polygonTriangulation(poly);
assert(int(tris.size()) == int(poly.size()) - 2);
for (auto &&t : tris) {
T ta2 = area2(t[0], t[1], t[2]);
assert(lt(0, ta2));
sm += ta2;
}
assert(eq(a2, sm));
checkSum += a2;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Grid) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
long long checkSum = 0;
vector<pt> poly = {pt(0, 0), pt(1, 0), pt(2, 0), pt(2, -1), pt(2, -2), pt(3, -2), pt(4, -2), pt(4, 0), pt(5, 0), pt(6, 0), pt(6, 1), pt(5, 1), pt(4, 1), pt(4, 3), pt(3, 3), pt(2, 3), pt(2, 2), pt(2, 1), pt(1, 1), pt(0, 1)};
assert(int(poly.size()) == 20);
T a2 = getArea2(poly), sm = 0;
auto tris = polygonTriangulation(poly);
assert(int(tris.size()) == int(poly.size()) - 2);
for (auto &&t : tris) {
T ta2 = area2(t[0], t[1], t[2]);
assert(lt(0, ta2));
sm += ta2;
}
assert(eq(a2, sm));
checkSum += a2;
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Special) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
long long checkSum = 0;
vector<pt> poly = {pt(6, 5), pt(0, 5), pt(0, 4), pt(1, 4), pt(1, 3), pt(0, 3), pt(0, 2), pt(1, 2), pt(1, 1), pt(0, 1), pt(0, 0), pt(6, 0), pt(6, 1), pt(5, 1), pt(5, 2), pt(6, 2), pt(6, 3), pt(5, 3), pt(5, 4), pt(6, 4)};
assert(int(poly.size()) == 20);
T a2 = getArea2(poly), sm = 0;
auto tris = polygonTriangulation(poly);
assert(int(tris.size()) == int(poly.size()) - 2);
for (auto &&t : tris) {
T ta2 = area2(t[0], t[1], t[2]);
assert(lt(0, ta2));
sm += ta2;
}
assert(eq(a2, sm));
checkSum += a2;
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Special) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/geometry/2d/BentleyOttmann.h"
#include "../../../../Content/C++/geometry/2d/Line.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
vector<pair<pt, pt>> segs;
for (int i = 0; i < 10; i++) {
T a, b, c;
do {
a = int(rng() % 21) - 10;
b = int(rng() % 21) - 10;
c = int(rng() % 401) - 201;
} while (a == 0 && b == 0);
Line l(a, b, c);
while (rng() % 2) {
pt p = l.proj(pt(int(rng() % 21) - 10, int(rng() % 21) - 10));
pt q = l.proj(pt(int(rng() % 21) - 10, int(rng() % 21) - 10));
segs.emplace_back(p, q);
}
}
set<pair<int, int>> ans0, ans1;
bentleyOttmann(segs, [&] (int i, int j) {
if (i > j) swap(i, j);
ans0.emplace(i, j);
});
for (int i = 0; i < int(segs.size()); i++) for (int j = i + 1; j < int(segs.size()); j++) {
if (segSegIntersects(segs[i].first, segs[i].second, segs[j].first, segs[j].second)) ans1.emplace(i, j);
}
assert(ans0 == ans1);
for (auto &&p : ans0) {
checkSum = 31 * checkSum + p.first;
checkSum = 31 * checkSum + p.second;
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/geometry/2d/FarthestPair.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 7;
vector<pt> P(N);
for (auto &&p : P) p = pt(int(rng() % int(10) - int(5)), int(rng() % int(10) - int(5)));
FarthestPair fp(P);
T mx = 0;
for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) mx = max(mx, distSq(P[i], P[j]));
assert(eq(mx, fp.bestDistSq));
checkSum = 31 * checkSum + fp.bestDistSq;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/geometry/2d/MinTriangleArea.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 2e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
vector<pt> P(N);
for (auto &&p : P) p = pt(rng() % int(10), rng() % int(10));
T minArea2 = numeric_limits<T>::max();
for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) for (int k = 0; k < j; k++)
minArea2 = min(minArea2, abs(area2(P[i], P[j], P[k])));
MinTriangleArea mta(P);
assert(minArea2 == mta.minArea2);
if (minArea2 != numeric_limits<T>::max()) assert(area2(mta.PA, mta.PB, mta.PC) == minArea2);
checkSum = 31 * checkSum + minArea2;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/geometry/2d/Line.h"
#include "../../../../Content/C++/geometry/2d/Angle.h"
#include "../../../../Content/C++/geometry/2d/Circle.h"
#include "../../../../Content/C++/geometry/2d/Polygon.h"
#include "../../../../Content/C++/geometry/2d/IncrementalConvexHull.h"
using namespace std;
vector<pt> generateConvexPolygon(int N, mt19937_64 &rng) {
uniform_real_distribution<T> dis(0, 1);
vector<T> X(N), Y(N);
for (int i = 0; i < N; i++) X[i] = dis(rng);
for (int i = 0; i < N; i++) Y[i] = dis(rng);
sort(X.begin(), X.end());
sort(Y.begin(), Y.end());
T xmin = X[0], xmax = X[N - 1], ymin = Y[0], ymax = Y[N - 1];
vector<T> xv, yv;
T lastTop = xmin, lastBot = xmin;
for (int i = 1; i < N - 1; i++) {
if (rng() % 2) {
xv.push_back(X[i] - lastTop);
lastTop = X[i];
} else {
xv.push_back(lastBot - X[i]);
lastBot = X[i];
}
}
xv.push_back(xmax - lastTop);
xv.push_back(lastBot - xmax);
T lastLeft = ymin, lastRight = ymin;
for (int i = 1; i < N - 1; i++) {
if (rng() % 2) {
yv.push_back(Y[i] - lastLeft);
lastLeft = Y[i];
} else {
yv.push_back(lastRight - Y[i]);
lastRight = Y[i];
}
}
yv.push_back(ymax - lastLeft);
yv.push_back(lastRight - ymax);
shuffle(yv.begin(), yv.end(), rng);
vector<pt> V(N), P;
for (int i = 0; i < N; i++) V[i] = pt(xv[i], yv[i]);
sort(V.begin(), V.end(), [&] (pt a, pt b) {
return Angle(a) < Angle(b);
});
T x = 0, xminPoly = 0, y = 0, yminPoly = 0;
for (int i = 0; i < N; i++) {
P.emplace_back(x, y);
xminPoly = min(xminPoly, x += V[i].x);
yminPoly = min(yminPoly, y += V[i].y);
}
x = xmin - xminPoly;
y = ymin - yminPoly;
for (int i = 0; i < N; i++) P[i] += pt(x, y);
for (int i = 0; i < N; i++) for (int j = 0; j < N; j++)
assert(segSegIntersects(P[i], P[mod(i + 1, N)], P[j], P[mod(j + 1, N)]) != 1);
if (N == 2) assert(P[0] != P[1]);
if (N >= 3) for (int i = 0; i < N; i++) assert(ccw(P[mod(i + N - 1, N)], P[i], P[mod(i + 1, N)]) > 0);
return P;
}
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 10 + 1;
vector<pt> poly = generateConvexPolygon(N, rng);
IncrementalConvexHull ch;
for (auto &&p : poly) assert(ch.addPoint(p));
int Q = 100;
uniform_real_distribution<T> dis(-10, 10);
for (int i = 0; i < Q; i++) {
pt p;
do {
p = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
if (N >= 2 && rng() % 10 == 0) {
int j = rng() % N;
int k = mod(j + 1, N);
if (rng() % 2) swap(j, k);
p = poly[j] * T(2) - poly[k];
}
pair<int, int> tangent = convexPolygonPointTangent(poly, p);
assert(0 <= tangent.first && tangent.first < N);
assert(0 <= tangent.second && tangent.second < N);
checkSum = 31 * checkSum + tangent.first;
checkSum = 31 * checkSum + tangent.second;
if (N == 1) {
assert(tangent.first == tangent.second);
} else if (N == 2) {
if (tangent.first == tangent.second) assert(ccw(poly[0], poly[1], p) == 0);
} else assert(tangent.first != tangent.second);
Line l1(p, poly[tangent.first]), l2(p, poly[tangent.second]);
for (int j = 0; j < N; j++) {
assert(l1.onLeft(poly[j]) < 0 || (l1.onLeft(poly[j]) == 0 && le(distSq(p, poly[tangent.first]), distSq(p, poly[j]))));
assert(l2.onLeft(poly[j]) > 0 || (l2.onLeft(poly[j]) == 0 && le(distSq(p, poly[tangent.second]), distSq(p, poly[j]))));
}
auto tangent2 = ch.pointTangents(p);
assert(poly[tangent.first] == tangent2.first->p);
assert(poly[tangent.second] == tangent2.second->p);
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Convex Polygon Point Tangent) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e3;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 10 + 1;
vector<pt> poly = generateConvexPolygon(N, rng);
IncrementalConvexHull ch;
for (auto &&p : poly) assert(ch.addPoint(p));
int Q = 100;
uniform_real_distribution<T> dis(-10, 10), dis2(0, 10);
for (int i = 0; i < Q; i++) {
pt p;
do {
p = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
if (N >= 2 && rng() % 10 == 0) {
int j = rng() % N;
int k = mod(j + 1, N);
if (rng() % 2) swap(j, k);
p = poly[j] * T(2) - poly[k];
}
T r;
int iter = 0;
auto good = [&] {
if (iter++ >= 100000) {
do {
p = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
iter = 0;
}
if (gt(polygonCircleIntersectionArea(poly, Circle(p, r)), 0)) return false;
for (int j = 0; j < N; j++) if (Circle(p, r).contains(poly[j]) >= 0) return false;
if (N > 1) for (int j = 0; j < N; j++) {
vector<pt> inter = circleLineIntersection(Circle(p, r), Line(poly[j], poly[mod(j + 1, N)]));
if (!inter.empty() && !segSegIntersection(poly[j], poly[mod(j + 1, N)], inter[0], inter.back()).empty()) return false;
}
return true;
};
do {
r = dis2(rng);
} while (!good());
if (rng() % 10 == 0) r = 0;
bool inner = rng() % 2;
Circle c(p, r);
pair<int, int> tangent = convexPolygonCircleTangent(poly, c, inner);
assert(0 <= tangent.first && tangent.first < N);
assert(0 <= tangent.second && tangent.second < N);
checkSum = 31 * checkSum + tangent.first;
checkSum = 31 * checkSum + tangent.second;
if (N == 1) {
assert(tangent.first == tangent.second);
}
if (r == 0) {
assert(tangent == convexPolygonPointTangent(poly, p));
} else {
vector<pair<pt, pt>> t1, t2;
circleCircleTangent(Circle(poly[tangent.first], 0), c, inner, t1);
circleCircleTangent(Circle(poly[tangent.second], 0), c, inner, t2);
pt a = t1[0].second, b = t2[1].second;
Line l1(a, poly[tangent.first]), l2(b, poly[tangent.second]);
if (inner) {
assert(eq(circleHalfPlaneIntersectionArea(c, Line(-l1.v, -l1.c)), 0));
assert(eq(circleHalfPlaneIntersectionArea(c, l2), 0));
} else {
assert(eq(circleHalfPlaneIntersectionArea(c, l1), 0));
assert(eq(circleHalfPlaneIntersectionArea(c, Line(-l2.v, -l2.c)), 0));
}
for (int j = 0; j < N; j++) {
assert(l1.onLeft(poly[j]) < 0 || (l1.onLeft(poly[j]) == 0 && le(distSq(a, poly[tangent.first]), distSq(a, poly[j]))));
assert(l2.onLeft(poly[j]) > 0 || (l2.onLeft(poly[j]) == 0 && le(distSq(b, poly[tangent.second]), distSq(b, poly[j]))));
}
}
auto tangent2 = ch.circleTangents(c, inner);
assert(poly[tangent.first] == tangent2.first->p);
assert(poly[tangent.second] == tangent2.second->p);
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Convex Polygon Circle Tangent) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 10 + 1, M = rng() % 10 + 1;
bool inner = rng() % 2;
vector<pt> poly1 = generateConvexPolygon(N, rng), poly2 = generateConvexPolygon(M, rng);
pt add = rng() % 2 ? pt(1, 0) : pt(0, 1);
for (auto &&p : poly2) p += add;
if (rng() % 2) {
swap(N, M);
swap(poly1, poly2);
}
IncrementalConvexHull ch1, ch2;
for (auto &&p : poly1) assert(ch1.addPoint(p));
for (auto &&p : poly2) assert(ch2.addPoint(p));
vector<pair<int, int>> tangent = convexPolygonConvexPolygonTangent(poly1, poly2, inner);
assert(0 <= tangent[0].first && tangent[0].first < N);
assert(0 <= tangent[1].first && tangent[1].first < N);
assert(0 <= tangent[0].second && tangent[0].second < M);
assert(0 <= tangent[1].second && tangent[1].second < M);
checkSum = 31 * checkSum + tangent[0].first;
checkSum = 31 * checkSum + tangent[0].second;
checkSum = 31 * checkSum + tangent[1].first;
checkSum = 31 * checkSum + tangent[1].second;
pt a = poly1[tangent[0].first], b = poly1[tangent[1].first], c = poly2[tangent[0].second], d = poly2[tangent[1].second];
Line l1(a, c), l2(b, d);
for (int i = 0; i < N; i++) {
assert(l1.onLeft(poly1[i]) > 0 || (l1.onLeft(poly1[i]) == 0 && le(distSq(c, a), distSq(c, poly1[i]))));
assert(l2.onLeft(poly1[i]) < 0 || (l2.onLeft(poly1[i]) == 0 && le(distSq(d, b), distSq(d, poly1[i]))));
}
for (int i = 0; i < M; i++) {
assert(l1.onLeft(poly2[i]) == (inner ? -1 : 1) || (l1.onLeft(poly2[i]) == 0 && le(distSq(a, c), distSq(a, poly2[i]))));
assert(l2.onLeft(poly2[i]) == (inner ? 1 : -1) || (l2.onLeft(poly2[i]) == 0 && le(distSq(b, d), distSq(b, poly2[i]))));
}
auto tangent2 = ch1.hullTangents(ch2, inner);
assert(a == tangent2[0].first->p);
assert(b == tangent2[1].first->p);
assert(c == tangent2[0].second->p);
assert(d == tangent2[1].second->p);
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Convex Polygon Convex Polygon Tangent) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 10 + 1;
vector<pt> poly = generateConvexPolygon(N, rng);
IncrementalConvexHull ch;
for (auto &&p : poly) assert(ch.addPoint(p));
int Q = 100;
uniform_real_distribution<T> dis(-10, 10);
for (int i = 0; i < Q; i++) {
pt p;
do {
p = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
if (N >= 2 && rng() % 10 == 0) {
int j = rng() % N;
int k = mod(j + 1, N);
if (rng() % 2) swap(j, k);
p = poly[j] * T(2) - poly[k];
}
pt closest = closestPointOnConvexPolygon(poly, p);
for (int j = 0; j < N; j++) {
pt q = closestPtOnSeg(p, poly[j], poly[mod(j + 1, N)]);
assert(le(distSq(p, closest), distSq(p, q)));
}
checkSum = 31 * checkSum + distSq(p, closest);
pt closest2 = ch.closestPt(p);
assert(eq(distSq(closest, closest2), 0));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Closest Point on Convex Polygon) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 10 + 1;
vector<pt> poly = generateConvexPolygon(N, rng);
IncrementalConvexHull ch;
for (auto &&p : poly) assert(ch.addPoint(p));
int Q = 100;
uniform_real_distribution<T> dis(-10, 10);
for (int i = 0; i < Q; i++) {
pt p;
do {
p = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
pt q;
do {
q = pt(dis(rng), dis(rng));
} while (isInConvexPolygon(poly, p) >= 0);
if (N >= 2 && rng() % 10 == 0) {
int j = rng() % N;
p = poly[j];
if (rng() % 2) q = poly[mod(j + 1, N)];
}
Line l(p, q);
pair<int, int> sides = convexPolygonLineIntersection(poly, l);
vector<pt> ans0, ans1, ans2 = ch.lineIntersection(l);
auto addToVec = [&] (vector<pt> &v, int i) {
pt a = poly[i], b = poly[mod(i + 1, N)];
if (a != b) {
pt c;
lineLineIntersection(l, Line(a, b), c);
if (onSeg(c, a, b)) v.push_back(c);
}
if (l.onLeft(a) == 0) v.push_back(a);
if (l.onLeft(b) == 0) v.push_back(b);
};
auto clean = [&] (vector<pt> &v) {
sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());
};
if (sides.first != -1) addToVec(ans1, sides.first);
if (sides.second != -1) addToVec(ans1, sides.second);
for (int j = 0; j < N; j++) addToVec(ans0, j);
clean(ans0);
clean(ans1);
assert(ans0 == ans1);
assert(ans0 == ans2);
for (pt a : ans0) {
checkSum = 31 * checkSum + 1e9 * a.x;
checkSum = 31 * checkSum + 1e9 * a.y;
}
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Line Convex Polygon Intersection) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/dp/LongestIncreasingSubsequence.h"
#include "../../../Content/C++/dp/LongestIncreasingSubsequenceFenwick.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int N = 1e7;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(6) + 1;
const auto start_time = chrono::system_clock::now();
vector<int> inds = longestIncreasingSubsequence(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (lower_bound) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int i : inds) checkSum = 31 * checkSum + i;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int N = 1e7;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(6) + 1;
const auto start_time = chrono::system_clock::now();
vector<int> inds = longestIncreasingSubsequenceFenwick(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Fenwick) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (int i : inds) checkSum = 31 * checkSum + i;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/dp/SubsetSum.h"
using namespace std;
const int M = 100;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(10) + 1;
bitset<M + 1> possible = subsetSum<M>(A);
int tot = accumulate(A.begin(), A.end(), 0);
vector<int> cnt(tot + 1, 0), dp = subsetSumCount<int>(A, tot);
for (int mask = 0; mask < (1 << N); mask++) {
int sm = 0;
for (int i = 0; i < N; i++) if ((mask >> i) & 1) sm += A[i];
cnt[sm]++;
}
assert(cnt == dp);
for (int i = 0; i < int(cnt.size()); i++) assert(possible[i] == bool(cnt[i]));
for (int i : dp) checkSum = 31 * checkSum + i;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/dp/MultisubsetSum.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int N = 3e4, M = 3e4;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(1e3) + 1;
const auto start_time = chrono::system_clock::now();
auto dp = multisubsetSum<bool>(A, M);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (bool) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&i : dp) checkSum = 31 * checkSum + i;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int N = 3e4, M = 3e4;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(1e3) + 1;
const auto start_time = chrono::system_clock::now();
auto dp = multisubsetSum<char>(A, M);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (char) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&i : dp) checkSum = 31 * checkSum + i;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
mt19937_64 rng(0);
int N = 3e4, M = 3e4;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(1e3) + 1;
const auto start_time = chrono::system_clock::now();
auto dp = multisubsetSum<int>(A, M);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (int) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&i : dp) checkSum = 31 * checkSum + i;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/dp/LongestIncreasingSubsequence.h"
#include "../../../Content/C++/dp/LongestIncreasingSubsequenceFenwick.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 7;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(6) + 1;
vector<int> maxInds;
for (int mask = 1; mask < (1 << N); mask++) {
vector<int> inds;
for (int i = 0; i < N; i++) if ((mask >> i) & 1) inds.push_back(i);
bool good = true;
for (int i = 0; i < int(inds.size()) - 1 && good; i++) good &= A[inds[i]] < A[inds[i + 1]];
if (good && make_pair(int(inds.size()), inds) > make_pair(int(maxInds.size()), maxInds)) maxInds = inds;
}
vector<int> inds = longestIncreasingSubsequence(A);
assert(inds == maxInds);
for (int i : inds) checkSum = 31 * checkSum + i;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (lower_bound) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 7;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(6) + 1;
vector<int> minB;
for (int mask = 1; mask < (1 << N); mask++) {
vector<int> B;
for (int i = 0; i < N; i++) if ((mask >> i) & 1) B.push_back(A[i]);
bool good = true;
for (int i = 0; i < int(B.size()) - 1 && good; i++) good &= B[i] < B[i + 1];
if (good && make_pair(-int(B.size()), B) < make_pair(-int(minB.size()), minB)) minB = B;
}
vector<int> inds = longestIncreasingSubsequenceFenwick(A), B;
for (int i : inds) B.push_back(A[i]);
assert(B == minB);
for (int i : inds) checkSum = 31 * checkSum + i;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Fenwick) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/math/Combinatorics.h"
#include "../../../Content/C++/math/ModularArithmetic.h"
using namespace std;
const long long MOD1 = 1e9, MOD2 = 1e9 + 7;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 20;
long long checkSum = 0;
vector<long long> ans0, ans1, ans2;
Combinatorics<long long> C(N);
for (int ti = 0; ti < TESTCASES; ti++) {
long long n = rng() % (N + 1);
ans0.push_back(factorial(n) % MOD1);
ans1.push_back(factorialMod(n, MOD1));
ans2.push_back(C.factorial(n) % MOD1);
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
assert(ans0 == ans2);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Factorial Mod) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 50;
long long checkSum = 0;
vector<long long> ans0, ans1;
CombinatoricsModPrime<long long> C(N, MOD2);
for (int ti = 0; ti < TESTCASES; ti++) {
long long n = rng() % (N + 1);
ans0.push_back(factorialMod(n, MOD2));
ans1.push_back(C.factorial(n));
assert(mulMod(C.factorial(n), C.invFactorial(n), MOD2) == 1);
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Factorial Mod Prime) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 20;
long long checkSum = 0;
vector<long long> ans0, ans1, ans2, ans3;
Combinatorics<long long> C(N);
for (int ti = 0; ti < TESTCASES; ti++) {
long long n = rng() % (N + 1), k = rng() % (n + 1);
ans0.push_back(factorial(n) / factorial(n - k) % MOD1);
ans1.push_back(permute(n, k) % MOD1);
ans2.push_back(permuteMod(n, k, MOD1));
ans3.push_back(C.permute(n, k) % MOD1);
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
assert(ans0 == ans2);
assert(ans0 == ans3);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Permute Mod) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 50;
long long checkSum = 0;
vector<long long> ans0, ans1, ans2;
CombinatoricsModPrime<long long> C(N, MOD2);
for (int ti = 0; ti < TESTCASES; ti++) {
long long n = rng() % (N + 1), k = rng() % (n + 1);
ans0.push_back(divModPrime(factorialMod(n, MOD2), factorialMod(n - k, MOD2), MOD2));
ans1.push_back(permuteMod(n, k, MOD2));
ans2.push_back(C.permute(n, k));
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
assert(ans0 == ans2);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Permute Mod Prime) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 20;
long long checkSum = 0;
vector<long long> ans0, ans1, ans2;
Combinatorics<long long> C(N);
for (int ti = 0; ti < TESTCASES; ti++) {
if (rng() % 2) {
long long n = rng() % (N + 1), k = rng() % (n + 1);
ans0.push_back(factorial(n) / factorial(n - k) / factorial(k));
ans1.push_back(choose(n, k));
ans2.push_back(C.choose(n, k));
} else {
long long n = rng() % (N / 2) + 1, k = rng() % (N / 2);
ans0.push_back(factorial(n + k - 1) / factorial(n - 1) / factorial(k));
ans1.push_back(multiChoose(n, k));
ans2.push_back(C.multiChoose(n, k));
}
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
assert(ans0 == ans2);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Combinations) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 50;
long long checkSum = 0;
vector<long long> ans0, ans1, ans2;
CombinatoricsModPrime<long long> C(N, MOD2);
for (int ti = 0; ti < TESTCASES; ti++) {
if (rng() % 2) {
long long n = rng() % (N + 1), k = rng() % (n + 1);
ans0.push_back(divModPrime(divModPrime(factorialMod(n, MOD2), factorialMod(n - k, MOD2), MOD2), factorialMod(k, MOD2), MOD2));
ans1.push_back(chooseModPrime(n, k, MOD2));
ans2.push_back(C.choose(n, k));
} else {
long long n = rng() % (N / 2) + 1, k = rng() % (N / 2);
ans0.push_back(divModPrime(divModPrime(factorialMod(n + k - 1, MOD2), factorialMod(n - 1, MOD2), MOD2), factorialMod(k, MOD2), MOD2));
ans1.push_back(multiChooseModPrime(n, k, MOD2));
ans2.push_back(C.multiChoose(n, k));
}
checkSum = 31 * checkSum + ans0.back();
}
assert(ans0 == ans1);
assert(ans0 == ans2);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Combinations Mod Prime) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test7() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int N = 20;
long long checkSum = 0;
Combinatorics<long long> C(N);
vector<vector<long long>> A = pascalsTriangle<long long>(N), B = pascalsTriangleMod<long long>(N, MOD1);
for (int i = 0; i <= N; i++) {
assert(A[i] == pascalsRow<long long>(i));
for (int j = 0; j <= i; j++) {
assert(A[i][j] % MOD1 == C.choose(i, j) % MOD1);
assert(A[i][j] % MOD1 == B[i][j]);
checkSum = checkSum * 31 + A[i][j];
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 7 (Pascal's Triangle Mod) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test8() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int N = 1000;
long long checkSum = 0;
CombinatoricsModPrime<long long> C(N, MOD2);
vector<vector<long long>> A = pascalsTriangleMod<long long>(N, MOD2);
for (int i = 0; i <= N; i++) {
assert(A[i] == pascalsRowModPrime<long long>(i, MOD2));
for (int j = 0; j <= i; j++) {
assert(A[i][j] == C.choose(i, j));
checkSum = checkSum * 31 + A[i][j];
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 8 (Pascal's Triangle Mod Prime) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test9() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 20;
long long checkSum = 0;
vector<long long> ans0, ans1;
for (int ti = 0; ti < TESTCASES; ti++) {
if (rng() % 2) {
long long n = rng() % (N + 1);
long long sm = 0;
for (long long i = 0; i <= n; i++) sm += i;
ans0.push_back(sm);
ans1.push_back(sumTo(n));
} else {
long long a = rng() % (N + 1), b = rng() % (N + 1);
if (a > b) swap(a, b);
long long sm = 0;
for (long long i = a; i <= b; i++) sm += i;
ans0.push_back(sm);
ans1.push_back(sumBetween(a, b));
}
checkSum = checkSum * 31 + ans0.back();
}
assert(ans0 == ans1);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 9 (Summation) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test10() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 20, MAXVAL = 1e6;
long long checkSum = 0;
vector<long long> ans0, ans1;
for (int ti = 0; ti < TESTCASES; ti++) {
long long a1 = rng() % (MAXVAL * 2 + 1) - MAXVAL;
long long d = rng() % (MAXVAL * 2 + 1) - MAXVAL;
int n = rng() % N + 1;
long long v = a1, sm = a1;
for (int i = 2; i <= n; i++) {
v += d;
sm += v;
}
ans0.push_back(v);
ans1.push_back(arithSeq(a1, d, n));
checkSum = checkSum * 31 + ans0.back();
ans0.push_back(sm);
ans1.push_back(arithSeries(a1, d, n));
checkSum = checkSum * 31 + ans0.back();
}
assert(ans0 == ans1);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 10 (Arithmetic Sequence) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test11() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e6;
const int N = 10, MAXVAL = 10;
long long checkSum = 0;
vector<long long> ans0, ans1;
for (int ti = 0; ti < TESTCASES; ti++) {
long long a1 = rng() % (MAXVAL * 2 + 1) - MAXVAL;
long long r = rng() % (MAXVAL * 2 + 1) - MAXVAL;
int n = rng() % N + 1;
long long v = a1, sm = a1;
for (int i = 2; i <= n; i++) {
v *= r;
sm += v;
}
ans0.push_back(v);
ans1.push_back(geoSeq(a1, r, n));
checkSum = checkSum * 31 + ans0.back();
ans0.push_back(sm);
ans1.push_back(geoSeries(a1, r, n));
checkSum = checkSum * 31 + ans0.back();
}
assert(ans0 == ans1);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 11 (Geometric Sequence) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/math/Matrix.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e4, OPS = 10;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11, M = rng() % 11;
Matrix<long long> A = makeMatrix<long long>(N, M), B = A;
for (int k = 0; k < OPS; k++) {
Matrix<long long> C = makeMatrix<long long>(N, M);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) C[i][j] = rng() % int(1e9);
A = A + C;
B = B - C;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) checkSum = 31 * checkSum + A[i][j];
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) checkSum = 31 * checkSum + B[i][j];
}
assert((A + B) == makeMatrix<long long>(N, M));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/math/Nimber.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e3;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
uint64_t a = 0;
while (a == 0) a = rng();
uint64_t inv = mulInvNim(a);
assert(mulNim(a, inv) == 1);
checkSum = 31 * checkSum + inv;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/math/GCD.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int m = rng() % 100 + 1, a = rng() % m, c = rng() % m;
pair<int, int> x = solveCongruence(a, c, m);
for (int i = 0; i < 1000; i++) assert((a * i % m == c) == (i % x.second == x.first));
checkSum = 31 * checkSum + x.first;
checkSum = 31 * checkSum + x.second;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/string/LongestCommonPrefix.h"
#include "../../../Content/C++/string/SuffixArray.h"
#include "../../../Content/C++/string/SAISSuffixArray.h"
using namespace std;
int lcp(const vector<int> &A, const vector<int> &B) {
int i = 0;
for (; i < min(int(A.size()), int(B.size())); i++) if (A[i] != B[i]) break;
return i;
}
vector<int> suffix(const vector<int> &A, int i) {
return vector<int>(A.begin() + i, A.end());
}
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
vector<int> A(N, 0);
for (auto &&a : A) a = rng() % int(10) + 1e5;
LongestCommonPrefix<SuffixArray<int>> LCP1(A);
LongestCommonPrefix<SAISSuffixArray<int>> LCP2(A);
vector<pair<vector<int>, int>> suffixes;
for (int i = 0; i < N; i++) suffixes.emplace_back(suffix(A, i), i);
sort(suffixes.begin(), suffixes.end());
vector<int> inv(N, -1);
for (int i = 0; i < N; i++) {
assert(suffixes[i].second == LCP1.SA.ind[i]);
assert(suffixes[i].second == LCP2.SA.ind[i]);
inv[suffixes[i].second] = i;
checkSum = 31 * checkSum + LCP1.SA.ind[i];
}
for (int i = 0; i < N; i++) {
assert(inv[i] == LCP1.SA.rnk[i]);
assert(inv[i] == LCP2.SA.rnk[i]);
checkSum = 31 * checkSum + LCP1.SA.rnk[i];
}
for (int i = 0; i < N - 1; i++) {
assert(lcp(suffixes[i].first, suffixes[i + 1].first) == LCP1.SA.LCP[i]);
assert(lcp(suffixes[i].first, suffixes[i + 1].first) == LCP2.SA.LCP[i]);
checkSum = 31 * checkSum + LCP1.SA.LCP[i];
}
if (N > 0) {
assert(LCP1.SA.LCP[N - 1] == 0);
assert(LCP2.SA.LCP[N - 1] == 0);
}
for (int i = 0; i < N; i++) for (int j = i; j < N; j++) {
assert(lcp(suffix(A, i), suffix(A, j)) == LCP1.lcp(i, j));
assert(lcp(suffix(A, i), suffix(A, j)) == LCP2.lcp(i, j));
checkSum = 31 * checkSum + LCP1.lcp(i, j);
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/string/LongestCommonPrefix.h"
#include "../../../Content/C++/string/SuffixArray.h"
#include "../../../Content/C++/string/SAISSuffixArray.h"
using namespace std;
void test1() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
const auto start_time = chrono::system_clock::now();
SuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Random, large alphabet, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
const auto start_time = chrono::system_clock::now();
vector<int> tmp = A;
sort(tmp.begin(), tmp.end());
tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
for (auto &&ai : A) ai = lower_bound(tmp.begin(), tmp.end(), ai) - tmp.begin();
SAISSuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Random, large alphabet, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % N + 1;
const auto start_time = chrono::system_clock::now();
SuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Random, medium alphabet, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % N + 1;
const auto start_time = chrono::system_clock::now();
SAISSuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Random, medium alphabet, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 26 + 1;
const auto start_time = chrono::system_clock::now();
SuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Random, small alphabet, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 26 + 1;
const auto start_time = chrono::system_clock::now();
SAISSuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Random, small alphabet, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test7() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> B(500);
for (auto &&bi : B) bi = rng() % N + 1;
vector<int> A(N);
for (int i = 0; i < N; i++) A[i] = B[i % 500];
const auto start_time = chrono::system_clock::now();
SuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 7 (Period 500, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test8() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> B(500);
for (auto &&bi : B) bi = rng() % N + 1;
vector<int> A(N);
for (int i = 0; i < N; i++) A[i] = B[i % 500];
const auto start_time = chrono::system_clock::now();
SAISSuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 8 (Period 500, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test9() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N, rng() % N + 1);
const auto start_time = chrono::system_clock::now();
SuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 9 (Period 1, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test10() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N, rng() % N + 1);
const auto start_time = chrono::system_clock::now();
SAISSuffixArray<int> SA(A);
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 10 (Period 1, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : SA.ind) checkSum = 31 * checkSum + a;
for (auto &&a : SA.rnk) checkSum = 31 * checkSum + a;
for (auto &&a : SA.LCP) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test11() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N, rng() % N + 1);
const auto start_time = chrono::system_clock::now();
LongestCommonPrefix<SuffixArray<int>> LCP(A);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) ans.push_back(LCP.lcp(rng() % N, rng() % N));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 11 (lcp queries, SuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test12() {
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N, rng() % N + 1);
const auto start_time = chrono::system_clock::now();
LongestCommonPrefix<SAISSuffixArray<int>> LCP(A);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) ans.push_back(LCP.lcp(rng() % N, rng() % N));
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 12 (lcp queries, SAISSuffixArray) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11();
test12();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/SparseTable.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
struct Min { int operator () (int a, int b) { return min(a, b); } };
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(1e9) + 1;
SparseTable<int, Min> ST(A);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
int mn = A[l];
for (int j = l + 1; j <= r; j++) mn = min(mn, A[j]);
ans0.push_back(mn);
ans1.push_back(ST.query(l, r));
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/DisjointSparseTable.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
static constexpr const long long MOD = 1e9;
struct MulMod { long long operator () (long long a, long long b) { return a * b % MOD; } };
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<long long> A(N);
for (auto &&a : A) a = rng() % int(1e9) + 1;
DisjointSparseTable<long long, MulMod> ST(A);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long prod = A[l];
for (int j = l + 1; j <= r; j++) prod = prod * A[j] % MOD;
ans0.push_back(prod);
ans1.push_back(ST.query(l, r));
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/PrefixSumArray2D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
long long A[10][20], B[10][20];
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[i][j] = A[i][j] = rng() % int(1e6) + 1;
adjacent_difference_2d(B, N, M, B);
int U = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e6) + 1;
add(B, N, M, u, d, l, r, v);
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) A[j][k] += v;
}
partial_sum_2d(B, N, M, B);
partial_sum_2d(B, N, M, B);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans0.push_back(rsq(B, u, d, l, r));
long long sm = 0;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans1.push_back(sm);
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (C style array) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
array<array<long long, 20>, 10> A, B;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[i][j] = A[i][j] = rng() % int(1e6) + 1;
adjacent_difference_2d(B, N, M, B);
int U = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e6) + 1;
add(B, N, M, u, d, l, r, v);
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) A[j][k] += v;
}
partial_sum_2d(B, N, M, B);
partial_sum_2d(B, N, M, B);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans0.push_back(rsq(B, u, d, l, r));
long long sm = 0;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans1.push_back(sm);
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (std::array) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M)), B(N, vector<long long>(M));
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[i][j] = A[i][j] = rng() % int(1e6) + 1;
adjacent_difference_2d(B, N, M, B);
int U = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e6) + 1;
add(B, N, M, u, d, l, r, v);
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) A[j][k] += v;
}
partial_sum_2d(B, N, M, B);
partial_sum_2d(B, N, M, B);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans0.push_back(rsq(B, u, d, l, r));
long long sm = 0;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans1.push_back(sm);
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (std::vector) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/PrefixSumArray2D.h"
using namespace std;
long long A[4000][6000];
array<array<long long, 6000>, 4000> B;
vector<vector<long long>> C(4000, vector<long long>(6000));
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 4000;
constexpr const int M = 6000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) A[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(A, N, M, A);
int U = 1;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(A, N, M, u, d, l, r, v);
}
partial_sum_2d(A, N, M, A);
partial_sum_2d(A, N, M, A);
int Q = 1;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(A, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (C style array) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 500;
constexpr const int M = 1000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) A[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(A, N, M, A);
int U = 5e6;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(A, N, M, u, d, l, r, v);
}
partial_sum_2d(A, N, M, A);
partial_sum_2d(A, N, M, A);
int Q = 5e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(A, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (C style array) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 4000;
constexpr const int M = 6000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(B, N, M, B);
int U = 1;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(B, N, M, u, d, l, r, v);
}
partial_sum_2d(B, N, M, B);
partial_sum_2d(B, N, M, B);
int Q = 1;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(B, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (std::array) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 500;
constexpr const int M = 1000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(B, N, M, B);
int U = 5e6;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(B, N, M, u, d, l, r, v);
}
partial_sum_2d(B, N, M, B);
partial_sum_2d(B, N, M, B);
int Q = 5e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(B, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (std::array) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 4000;
constexpr const int M = 6000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) C[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(C, N, M, C);
int U = 1;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(C, N, M, u, d, l, r, v);
}
partial_sum_2d(C, N, M, C);
partial_sum_2d(C, N, M, C);
int Q = 1;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(C, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (std::vector) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 500;
constexpr const int M = 1000;
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) C[i][j] = rng() % int(1e5) + 1;
adjacent_difference_2d(C, N, M, C);
int U = 5e6;
for (int i = 0; i < U; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e5) + 1;
add(C, N, M, u, d, l, r, v);
}
partial_sum_2d(C, N, M, C);
partial_sum_2d(C, N, M, C);
int Q = 5e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(rsq(C, u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (std::vector) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/WaveletMatrixAggregation.h"
#include "../../../Content/C++/datastructures/trees/fenwicktrees/BitFenwickTree.h"
using namespace std;
struct R {
using Data = int;
using Lazy = int;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) { return l + r; }
BitFenwickTree FT;
R(const vector<Data> &A) : FT(A.size()) {
for (int i = 0; i < int(A.size()); i++) FT.set(i, A[i]);
FT.build();
}
void update(int i, const Lazy &val) { FT.update(i, val); }
Data query(int l, int r) { return FT.query(l, r); }
};
void test1() {
mt19937_64 rng(0);
constexpr const int N = 1e6, Q = 1e6, MAXA = 1e9;
long long checkSum = 0;
vector<int> A(N, 0);
for (int i = 0; i < N; i++) A[i] = rng() % MAXA;
vector<int> B(N, 0);
for (int i = 0; i < N; i++) B[i] = rng() % 2;
const auto start_time = chrono::system_clock::now();
WaveletMatrixAggregation<int, R> wm(A, B);
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 3;
if (t == 0) {
int j = rng() % N;
wm.update(j, B[j] ^= 1);
} else if (t == 1) {
int l = rng() % N, r = rng() % N, a = rng() % MAXA, b = rng() % MAXA;
if (l > r) swap(l, r);
if (a > b) swap(a, b);
ans.push_back(wm.query(l, r, a, b));
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
int k = rng() % ((wm.query(l, r, MAXA) + 1) * 2);
pair<bool, int *> p = wm.bsearch(l, r, [&] (int agg) {
return agg >= k;
});
ans.push_back(p.first ? *p.second : INT_MAX);
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/DisjointSparseTable.h"
#include "../../../Content/C++/datastructures/FischerHeunStructure.h"
#include "../../../Content/C++/datastructures/SparseTable.h"
#include "../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeBottomUp.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
SparseTable<int, Min> ST(A);
int Q = 1;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
SparseTable<int, Min> ST(A);
int Q = 1e7;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
DisjointSparseTable<int, Min> ST(A);
int Q = 1;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Disjoint Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
DisjointSparseTable<int, Min> ST(A);
int Q = 1e7;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Disjoint Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FischerHeunStructure<int, greater<int>> ST(A);
int Q = 1;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Fischer Heun) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FischerHeunStructure<int, greater<int>> ST(A);
int Q = 1e7;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Fischer Heun) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test7() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
struct Combine {
using Data = int;
using Lazy = int;
static Data qdef() { return numeric_limits<int>::max(); }
static Data merge(const Data &l, const Data &r) { return min(l, r); }
};
SegmentTreeBottomUp<Combine> ST(A);
int Q = 1;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 7 (Segment Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test8() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
struct Combine {
using Data = int;
using Lazy = int;
static Data qdef() { return numeric_limits<int>::max(); }
static Data merge(const Data &l, const Data &r) { return min(l, r); }
};
SegmentTreeBottomUp<Combine> ST(A);
int Q = 1e7;
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(ST.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 8 (Segment Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/WaveletMatrixAggregation.h"
#include "../../../Content/C++/datastructures/trees/fenwicktrees/BitFenwickTree.h"
using namespace std;
struct R {
using Data = int;
using Lazy = int;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) { return l + r; }
BitFenwickTree FT;
R(const vector<Data> &A) : FT(A.size()) {
for (int i = 0; i < int(A.size()); i++) FT.set(i, A[i]);
FT.build();
}
void update(int i, const Lazy &val) { FT.update(i, val); }
Data query(int l, int r) { return FT.query(l, r); }
};
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5, MAXA = 100;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<int> A(N, 0);
for (int i = 0; i < N; i++) A[i] = rng() % MAXA;
vector<int> B(N, 0);
for (int i = 0; i < N; i++) B[i] = rng() % 2;
WaveletMatrixAggregation<int, R> wm(A, B);
int Q = N == 0 ? 0 : rng() % 101;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 3;
if (t == 0) {
int j = rng() % N;
wm.update(j, B[j] ^= 1);
} else if (t == 1) {
int l = rng() % N, r = rng() % N, a = rng() % MAXA, b = rng() % MAXA;
if (l > r) swap(l, r);
if (a > b) swap(a, b);
int sm = 0;
for (int j = l; j <= r; j++) if (a <= A[j] && A[j] <= b) sm += B[j];
ans0.push_back(sm);
ans1.push_back(wm.query(l, r, a, b));
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
int k = rng() % ((wm.query(l, r, MAXA) + 1) * 2);
vector<int> C;
for (int j = l; j <= r; j++) if (B[j]) C.push_back(A[j]);
sort(C.begin(), C.end());
if (k == 0) ans0.push_back(*min_element(A.begin(), A.end()));
else if (k - 1 < int(C.size())) ans0.push_back(C[k - 1]);
else ans0.push_back(INT_MAX);
pair<bool, int *> p = wm.bsearch(l, r, [&] (int agg) {
return agg >= k;
});
ans1.push_back(p.first ? *p.second : INT_MAX);
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/SparseTable2D.h"
#include "../../../Content/C++/datastructures/FischerHeunStructure2D.h"
#include "../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeBottomUp2D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SparseTable2D<int, Min> ST(A);
int Q = 1;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(ST.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
struct Min { int operator () (int a, int b) { return min(a, b); } };
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SparseTable2D<int, Min> ST(A);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(ST.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Sparse Table) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FischerHeunStructure2D<int, greater<int>> FHS(A);
int Q = 1;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(FHS.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Fischer Heun Structure) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FischerHeunStructure2D<int, greater<int>> FHS(A);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(FHS.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Fischer Heun Structure) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
struct C {
using Data = int;
using Lazy = int;
static Data qdef() { return numeric_limits<int>::max(); }
static Data merge(const Data &l, const Data &r) {
return min(l, r);
}
static Data applyLazy(const Data &, const Lazy &r) {
return r;
}
};
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SegmentTreeBottomUp2D<C> ST(A);
int Q = 1;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(ST.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Segment Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 500, M = 1000;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SegmentTreeBottomUp2D<C> ST(A);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(ST.query(u, d, l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Segment Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/BitPrefixSumArray.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 1001;
vector<int> A(N + 1, 0);
BitPrefixSumArray bpsa(N);
int U = N == 0 ? 0 : 1000 - rng() % 5;
for (int i = 0; i < U; i++) {
int j = rng() % N, v = rng() % 2;
A[j + 1] = v;
bpsa.set(j, v);
}
for (int i = 0; i < N; i++) assert(A[i + 1] == bpsa.get(i));
partial_sum(A.begin(), A.end(), A.begin());
bpsa.build();
int Q = N == 0 ? 0 : 1000 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans0.push_back(A[r + 1] - A[l]);
ans1.push_back(bpsa.query(l, r));
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/SparseTable2D.h"
#include "../../../Content/C++/datastructures/FischerHeunStructure2D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
struct Min { int operator () (int a, int b) { return min(a, b); } };
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SparseTable2D<int, Min> ST(A);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
int mn = A[u][l];
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) mn = min(mn, A[j][k]);
ans0.push_back(mn);
ans1.push_back(ST.query(u, d, l, r));
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Sparse Table) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<int>> A(N, vector<int>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FischerHeunStructure2D<int, greater<int>> FHS(A);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
int mn = A[u][l];
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) mn = min(mn, A[j][k]);
ans0.push_back(mn);
ans1.push_back(FHS.query(u, d, l, r));
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Fischer Heun Structure) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/BitPrefixSumArray.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, U = 1e7, Q = 1e7;
vector<int> A(N + 1);
for (int i = 0; i < U; i++) {
int j = rng() % N, v = rng() % 2;
A[j + 1] = v;
}
partial_sum(A.begin(), A.end(), A.begin());
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(A[r + 1] - A[l]);
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Prefix Sum) Passed" << endl;
cout << " N: " << N << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, U = 1e7, Q = 1e7;
BitPrefixSumArray bpsa(N);
for (int i = 0; i < U; i++) {
int j = rng() % N, v = rng() % 2;
bpsa.set(j, v);
}
bpsa.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(bpsa.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Bit Prefix Sum) Passed" << endl;
cout << " N: " << N << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e9, U = 1e7, Q = 1e7;
BitPrefixSumArray bpsa(N);
for (int i = 0; i < U; i++) {
int j = rng() % N, v = rng() % 2;
bpsa.set(j, v);
}
bpsa.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(bpsa.query(l, r));
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Bit Prefix Sum) Passed" << endl;
cout << " N: " << N << endl;
cout << " U: " << U << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../Content/C++/datastructures/FischerHeunStructure.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(100) + 1;
FischerHeunStructure<int, greater<int>> FHS(A);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1, ansA0, ansA1;
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
int mnInd = l;
for (int j = l + 1; j <= r; j++) if (A[mnInd] > A[j]) mnInd = j;
ans0.push_back(mnInd);
ansA0.push_back(A[ans0.back()]);
ans1.push_back(FHS.queryInd(l, r));
ansA1.push_back(A[ans1.back()]);
}
assert(ans0 == ans1);
assert(ansA0 == ansA1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<int> A(N);
for (auto &&a : A) a = rng() % int(100) + 1;
FischerHeunStructure<int, greater_equal<int>> FHS(A);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1, ansA0, ansA1;
for (int i = 0; i < Q; i++) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
int mnInd = l;
for (int j = l + 1; j <= r; j++) if (A[mnInd] >= A[j]) mnInd = j;
ans0.push_back(mnInd);
ansA0.push_back(A[ans0.back()]);
ans1.push_back(FHS.queryInd(l, r));
ansA1.push_back(A[ans1.back()]);
}
assert(ans0 == ans1);
assert(ansA0 == ansA1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/unionfind/UnionFind.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
UnionFind uf(N);
vector<vector<int>> sets(N);
vector<int> par(N);
for (int i = 0; i < N; i++) sets[par[i] = i].push_back(i);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
if (rng() % 2 == 0) {
int v = rng() % N;
ans0.push_back(int(sets[par[v]].size()));
ans1.push_back(uf.getSize(v));
} else {
int v = rng() % N, w = rng() % N;
if (sets[par[v]].size() < sets[par[w]].size()) swap(v, w);
if (par[w] != par[v]) for (int x : sets[par[w]]) sets[par[x] = par[v]].push_back(x);
uf.join(v, w);
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/unionfind/UnionFind.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
UnionFind uf(N);
int Q = 1e7;
vector<int> ans;
for (int i = 0; i < Q; i++) {
if (rng() % 2 == 0) ans.push_back(uf.getSize(rng() % N));
else {
int v = rng() % N, w = rng() % N;
uf.join(v, w);
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/trees/BinaryTrie.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 100 + 1;
vector<int> A(N);
for (auto &&a : A) a = rng() % (1 << 30);
BinaryTrie<int> trie(1 << 30);
for (auto &&a : A) trie.insert(a);
int Q = 100 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int v = rng() % (1 << 30);
if (t == 0) {
int mn = INT_MAX;
for (auto &&a : A) mn = min(mn, v ^ a);
ans0.push_back(mn);
ans1.push_back(trie.minXor(v));
} else {
int mx = INT_MIN;
for (auto &&a : A) mx = max(mx, v ^ a);
ans0.push_back(mx);
ans1.push_back(trie.maxXor(v));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeAffine.h"
#include "../../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeAffine.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
FenwickTreeAffine<long long> FT(N);
SegmentTreeAffine<long long> ST(N);
vector<long long> A(N, 0);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1, ans2;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
if (t == 0) {
long long m = rng() % int(1e2) + 1;
long long b = rng() % int(1e2) + 1;
for (int j = l; j <= r; j++) A[j] += (j - l + 1) * m + b;
FT.update(l, r, m, b);
ST.update(l, r, m, b);
} else {
long long sm = 0;
for (int j = l; j <= r; j++) sm += A[j];
ans0.push_back(sm);
ans1.push_back(FT.query(l, r));
ans2.push_back(ST.query(l, r));
}
}
assert(ans0 == ans1);
assert(ans0 == ans2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeAffine.h"
#include "../../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeAffine.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
FenwickTreeAffine<long long> FT(N);
int Q = 2e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
if (t == 0) {
long long m = rng() % int(1e2) + 1;
long long b = rng() % int(1e2) + 1;
FT.update(l, r, m, b);
} else {
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Fenwick Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2e6;
SegmentTreeAffine<long long> ST(N);
int Q = 2e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
if (t == 0) {
long long m = rng() % int(1e2) + 1;
long long b = rng() % int(1e2) + 1;
ST.update(l, r, m, b);
} else {
ans.push_back(ST.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Segment Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeBottomUp2D.h"
using namespace std;
struct C {
using Data = long long;
using Lazy = long long;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) {
return l + r;
}
static Data applyLazy(const Data &l, const Lazy &r) {
return l + r;
}
};
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2000;
int M = 3000;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SegmentTreeBottomUp2D<C> ST(A);
int Q = 1e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N, j = rng() % M;
long long v = rng() % int(1e9) + 1;
ST.update(i, j, v);
} else {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(ST.query(u, d, l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeBottomUp2D.h"
using namespace std;
struct C {
using Data = long long;
using Lazy = long long;
static Data qdef() { return 0; }
static Data merge(const Data &l, const Data &r) {
return l + r;
}
static Data applyLazy(const Data &l, const Lazy &r) {
return l + r;
}
};
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SegmentTreeBottomUp2D<C> ST(A);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N, j = rng() % M;
long long v = rng() % int(1e9) + 1;
A[i][j] += v;
ST.update(i, j, v);
} else {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long sm = C::qdef();
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans0.push_back(sm);
ans1.push_back(ST.query(u, d, l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (2D vector constructor) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
SegmentTreeBottomUp2D<C> ST(N, M, 0);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ST.update(i, j, A[i][j]);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N, j = rng() % M;
long long v = rng() % int(1e9) + 1;
A[i][j] += v;
ST.update(i, j, v);
} else {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long sm = C::qdef();
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans0.push_back(sm);
ans1.push_back(ST.query(u, d, l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (vdef constructor) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 4000;
int M = 6000;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FenwickTree<2, long long> FT(N, M);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) FT.update(i, j, A[i][j]);
int Q = 1e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N, j = rng() % M;
long long v = rng() % int(1e9) + 1;
FT.update(i, j, v);
} else {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
ans.push_back(FT.query(u, d, l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint1D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTreeRangePoint1D<long long> FT(A);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
FT.update(l, r, v);
} else {
int j = rng() % N;
ans.push_back(FT.get(j));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (1D vector Constructor) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTreeRangePoint1D<long long> FT(N);
for (int i = 0; i < N; i++) FT.update(i, i, A[i]);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
FT.update(l, r, v);
} else {
int j = rng() % N;
ans.push_back(FT.get(j));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (1D default value constructor) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTreeRangePoint<1, long long> FT(N);
for (int i = 0; i < N; i++) FT.update(A[i], i, i);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
FT.update(v, l, r);
} else {
int j = rng() % N;
ans.push_back(FT.get(j));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (ND) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/BitFenwickTree.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree1D.h"
#include "../../../../../Content/C++/search/BinarySearch.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, Q = 1e7;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 2;
FenwickTree1D<int> FT(A);
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
FT.update(i, v - A[i]);
A[i] = v;
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (Fenwick Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, Q = 1e7;
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, rng() % 2);
BFT.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
BFT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(BFT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (Bit Fenwick Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e9, Q = 1e7;
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, rng() % 2);
BFT.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
BFT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(BFT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (Bit Fenwick Tree) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, Q = 1e7;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 2;
FenwickTree1D<int> FT(A);
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
FT.update(i, v - A[i]);
A[i] = v;
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
} else if (t == 2) {
int TOT = FT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(FT.bsearch(v, less<int>()));
} else if (t == 3) {
int TOT = FT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(FT.bsearch(v, less_equal<int>()));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (Fenwick Tree, lower_bound, upper_bound) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, Q = 1e7;
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, rng() % 2);
BFT.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
BFT.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(BFT.query(l, r));
} else if (t == 2) {
int TOT = BFT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(BFT.bsearch(v, less<int>()));
} else if (t == 3) {
int TOT = BFT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(BFT.bsearch(v, less_equal<int>()));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (Bit Fenwick Tree, lower_bound, upper_bound) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test6() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
constexpr const int N = 1e7, Q = 1e7;
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, rng() % 2);
BFT.build();
vector<int> ans;
ans.reserve(Q);
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
BFT.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(BFT.query(l, r));
} else if (t == 2) {
int TOT = BFT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return BFT.query(k) >= v;
}));
} else if (t == 3) {
int TOT = BFT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return BFT.query(k) > v;
}));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 6 (Bit Fenwick Tree, bsearch with query) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
test6();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/BitFenwickTree.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree1D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 1001;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 2;
FenwickTree1D<int> FT(A);
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, A[i]);
BFT.build();
int Q = N == 0 ? 0 : 1000 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
FT.update(i, v - A[i]);
A[i] = v;
BFT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans0.push_back(FT.query(l, r));
ans1.push_back(BFT.query(l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (point update, range query) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 5e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 1001;
vector<int> A(N);
for (auto &&ai : A) ai = rng() % 2;
FenwickTree1D<int> FT(A);
BitFenwickTree BFT(N);
for (int i = 0; i < N; i++) BFT.set(i, A[i]);
BFT.build();
int Q = N == 0 ? 0 : 1000 - rng() % 5;
vector<int> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
int v = rng() % 2;
FT.update(i, v - A[i]);
A[i] = v;
BFT.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans0.push_back(FT.query(l, r));
ans1.push_back(BFT.query(l, r));
} else if (t == 2) {
int TOT = FT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans0.push_back(FT.bsearch(v, less<int>()));
ans1.push_back(BFT.bsearch(v, less<int>()));
} else if (t == 3) {
int TOT = FT.query(N - 1) * 2 + 1;
int v = rng() % TOT;
ans0.push_back(FT.bsearch(v, less_equal<int>()));
ans1.push_back(BFT.bsearch(v, less_equal<int>()));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (point update, range query, binary search) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/RangeAddRangeSum2D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 2000;
int M = 3000;
RangeAddRangeSum2D<long long> ST(N, M);
int Q = 1e5;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
if (t == 0) {
long long v = rng() % int(1e9) + 1;
ST.update(u, d, l, r, v);
} else {
ans.push_back(ST.query(u, d, l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FenwickTreeRangePoint<2, long long> FT(N, M);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) FT.update(A[i][j], i, i, j, j);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) A[j][k] += v;
FT.update(v, u, d, l, r);
} else {
int i = rng() % N, j = rng() % M;
ans0.push_back(A[i][j]);
ans1.push_back(FT.get(i, j));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree1D.h"
#include "../../../../../Content/C++/search/BinarySearch.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTree1D<long long> FT1(N);
FenwickTree1D<long long> FT2(A);
FenwickTree<1, long long> FT3(N);
for (int i = 0; i < N; i++) {
FT1.update(i, A[i]);
FT3.update(i, A[i]);
}
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1, ans2, ans3;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e9) + 1;
A[i] += v;
FT1.update(i, v);
FT2.update(i, v);
FT3.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long sm = 0;
for (int j = l; j <= r; j++) sm += A[j];
ans0.push_back(sm);
ans1.push_back(FT1.query(l, r));
ans2.push_back(FT2.query(l, r));
ans3.push_back(FT3.query(l, r));
}
}
vector<long long> A1 = FT1.values(), A2 = FT2.values();
assert(ans0 == ans1);
assert(ans0 == ans2);
assert(ans0 == ans3);
assert(A == A1);
assert(A == A2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (point update, range query) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int maxVal = pow(10, rng() % 10);
int N = rng() % 101;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % maxVal + 1;
FenwickTree1D<long long> FT1(N);
FenwickTree1D<long long> FT2(A);
for (int i = 0; i < N; i++) FT1.update(i, A[i]);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1, ans2, ans3;
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
long long v = rng() % maxVal + 1;
A[i] += v;
FT1.update(i, v);
FT2.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long sm = 0;
for (int j = l; j <= r; j++) sm += A[j];
ans0.push_back(sm);
ans1.push_back(FT1.query(l, r));
ans2.push_back(FT2.query(l, r));
ans3.push_back(ans2.back());
} else if (t == 2) {
long long TOT = FT1.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
int j = 0;
long long sm = 0;
while (j < N && sm + A[j] < v) sm += A[j++];
ans0.push_back(j);
ans1.push_back(FT1.bsearch(v, less<long long>()));
ans2.push_back(FT2.bsearch(v, less<long long>()));
ans3.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return FT2.query(k) >= v;
}));
} else {
long long TOT = FT1.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
int j = 0;
long long sm = 0;
while (j < N && sm + A[j] <= v) sm += A[j++];
ans0.push_back(j);
ans1.push_back(FT1.bsearch(v, less_equal<long long>()));
ans2.push_back(FT2.bsearch(v, less_equal<long long>()));
ans3.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return FT2.query(k) > v;
}));
}
}
vector<long long> A1 = FT1.values(), A2 = FT2.values();
assert(ans0 == ans1);
assert(ans0 == ans2);
assert(ans0 == ans3);
assert(A == A1);
assert(A == A2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (point update, range query, binary search) Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRange1D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 5e6;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e4) + 1;
FenwickTreeRange1D<long long> FT(A);
int Q = 5e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e4) + 1;
FT.update(l, r, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/RangeAddRangeSum2D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e4;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 21;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M, 0));
RangeAddRangeSum2D<long long> ST(N, M);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
if (t == 0) {
long long v = rng() % int(1e9) + 1;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) A[j][k] += v;
ST.update(u, d, l, r, v);
} else {
long long sm = 0;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans0.push_back(sm);
ans1.push_back(ST.query(u, d, l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint1D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTreeRangePoint1D<long long> FT1(N);
FenwickTreeRangePoint1D<long long> FT2(A);
FenwickTreeRangePoint<1, long long> FT3(N);
for (int i = 0; i < N; i++) {
FT1.update(i, i, A[i]);
FT3.update(A[i], i, i);
}
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1, ans2, ans3;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
for (int j = l; j <= r; j++) A[j] += v;
FT1.update(l, r, v);
FT2.update(l, r, v);
FT3.update(v, l, r);
} else {
int j = rng() % N;
ans0.push_back(A[j]);
ans1.push_back(FT1.get(j));
ans2.push_back(FT2.get(j));
ans3.push_back(FT3.get(j));
}
}
vector<long long> A1 = FT1.values(), A2 = FT2.values();
assert(ans0 == ans1);
assert(ans0 == ans2);
assert(ans0 == ans3);
assert(A == A1);
assert(A == A2);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree.h"
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree1D.h"
#include "../../../../../Content/C++/search/BinarySearch.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e6) + 1;
FenwickTree1D<long long> FT(A);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e6) + 1;
FT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 (1D vector Constructor) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test2() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e6) + 1;
FenwickTree1D<long long> FT(N);
for (int i = 0; i < N; i++) FT.update(i, A[i]);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e6) + 1;
FT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 2 (1D default value constructor) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test3() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e6) + 1;
FenwickTree<1, long long> FT(N);
for (int i = 0; i < N; i++) FT.update(i, A[i]);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e6) + 1;
FT.update(i, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 3 (ND) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test4() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e6) + 1;
FenwickTree1D<long long> FT(A);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e6) + 1;
FT.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
} else if (t == 2) {
long long TOT = FT.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
ans.push_back(FT.bsearch(v, less<long long>()));
} else {
long long TOT = FT.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
ans.push_back(FT.bsearch(v, less_equal<long long>()));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 4 (lower_bound, upper_bound) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
void test5() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 1e7;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e6) + 1;
FenwickTree1D<long long> FT(A);
int Q = 1e7;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 4;
if (t == 0) {
int i = rng() % N;
long long v = rng() % int(1e6) + 1;
FT.update(i, v);
} else if (t == 1) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
ans.push_back(FT.query(l, r));
} else if (t == 2) {
long long TOT = FT.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
ans.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return FT.query(k) >= v;
}));
} else {
long long TOT = FT.query(N - 1) * 2 + 1;
long long v = rng() % TOT;
ans.push_back(bsearch<FIRST>(0, N, [&] (int k) {
return FT.query(k) > v;
}));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 5 (bsearch with query) Passed" << endl;
cout << " N: " << N << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
test2();
test3();
test4();
test5();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTree.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 11;
int M = rng() % 21;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FenwickTree<2, long long> FT(N, M);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) FT.update(i, j, A[i][j]);
int Q = N == 0 || M == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int i = rng() % N, j = rng() % M;
long long v = rng() % int(1e9) + 1;
A[i][j] += v;
FT.update(i, j, v);
} else {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long sm = 0;
for (int j = u; j <= d; j++) for (int k = l; k <= r; k++) sm += A[j][k];
ans0.push_back(sm);
ans1.push_back(FT.query(u, d, l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRangePoint.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
int N = 4000;
int M = 6000;
vector<vector<long long>> A(N, vector<long long>(M));
for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1;
FenwickTreeRangePoint<2, long long> FT(N, M);
for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) FT.update(A[i][j], i, i, j, j);
int Q = 1e6;
vector<long long> ans;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M;
if (u > d) swap(u, d);
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
FT.update(v, u, d, l, r);
} else {
int i = rng() % N, j = rng() % M;
ans.push_back(FT.get(i, j));
}
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " N: " << N << endl;
cout << " M: " << M << endl;
cout << " Q: " << Q << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
long long checkSum = 0;
for (auto &&a : ans) checkSum = 31 * checkSum + a;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#include <bits/stdc++.h>
#include "../../../../../Content/C++/datastructures/trees/fenwicktrees/FenwickTreeRange1D.h"
using namespace std;
void test1() {
const auto start_time = chrono::system_clock::now();
mt19937_64 rng(0);
const int TESTCASES = 1e5;
long long checkSum = 0;
for (int ti = 0; ti < TESTCASES; ti++) {
int N = rng() % 101;
vector<long long> A(N);
for (auto &&ai : A) ai = rng() % int(1e9) + 1;
FenwickTreeRange1D<long long> FT(A);
int Q = N == 0 ? 0 : 100 - rng() % 5;
vector<long long> ans0, ans1;
for (int i = 0; i < Q; i++) {
int t = rng() % 2;
if (t == 0) {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long v = rng() % int(1e9) + 1;
for (int j = l; j <= r; j++) A[j] += v;
FT.update(l, r, v);
} else {
int l = rng() % N, r = rng() % N;
if (l > r) swap(l, r);
long long sm = 0;
for (int j = l; j <= r; j++) sm += A[j];
ans0.push_back(sm);
ans1.push_back(FT.query(l, r));
}
}
assert(ans0 == ans1);
for (auto &&a : ans0) checkSum = 31 * checkSum + a;
}
const auto end_time = chrono::system_clock::now();
double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den));
cout << "Subtest 1 Passed" << endl;
cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl;
cout << " Checksum: " << checkSum << endl;
}
int main() {
test1();
cout << "Test Passed" << endl;
return 0;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#!/usr/bin/env bash
# first command line argument is the compile command, following arguments are
# the files to compile
numArgs=$#
declare -i total=0
declare -i pass=0
declare -i fail=0
for i in $(seq 2 $numArgs); do
test=${!i}
total+=1
echo ""
echo "$test:"
$1 $test
retCode=$?
if (($retCode == 0)); then
echo "Compiled Successfully"
pass+=1
else
fail+=1
fi
done
echo ""
echo "$total files(s) compiled"
echo "$pass successful"
echo "$fail failed"
if (($fail != 0)); then
exit 1
fi
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import argparse
import pathlib
parser = argparse.ArgumentParser(
description="Script to remove pramga once at the top of C++ header files "
"and replace them with header guards",
)
parser.add_argument("filenames", metavar="file", type=str, nargs="+")
filenames = parser.parse_args().filenames
replaced = 0
for filename in filenames:
print()
print(filename + ":")
headerguard = pathlib.Path(filename).stem.upper() + "_H"
output = []
with open(filename, "r") as file:
replacePragmaOnce = False
for line in file.read().splitlines():
if line == "#pragma once":
output.append("#ifndef " + headerguard)
output.append("#define " + headerguard)
output.append("")
replacePragmaOnce = True
else:
output.append(line)
if replacePragmaOnce:
output.append("")
output.append("#endif")
print("Replaced #pragma once")
replaced += 1
else:
print("Nothing to replace")
with open(filename, "w") as file:
file.write("\n".join(output) + "\n")
print()
print(len(filenames), "file(s) checked")
print(replaced, "file(s) modified")
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#!/usr/bin/env bash
# first command line argument is the compile command, following arguments are
# the files to compile
ulimit -s 524288
numArgs=$#
declare -i total=0
declare -i pass=0
declare -i fail=0
for i in $(seq 2 $numArgs); do
test=${!i}
total+=1
echo ""
echo "$test:"
$1 $test -o $test.o
retCode=$?
if (($retCode == 0)); then
timeout 5m ./$test.o
retCode=$?
if (($retCode == 0)); then
pass+=1
else
fail+=1
echo "Test Failed"
echo " Exit Code: $retCode"
fi
rm $test.o
else
fail+=1
echo "Failed to compile"
fi
done
echo ""
echo "$total test(s) ran"
echo "$pass passed"
echo "$fail failed"
if (($fail != 0)); then
exit 1
fi
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import argparse
import sys
parser = argparse.ArgumentParser(
description="Script to check that every line ends in \\n and not \\r\\n, "
"does not contain \\t, "
"and that every line does not exceed 79 characters",
)
parser.add_argument("filenames", metavar="file", type=str, nargs="+")
filenames = parser.parse_args().filenames
good = 0
bad = 0
for filename in filenames:
print()
print(filename + ":")
with open(filename, "rb") as file:
ok = True
for curLine, line in enumerate(file, 1):
if not line.endswith(b"\n"):
print(f"line {curLine} does not end in \\n")
ok = False
if line.endswith(b"\r\n"):
print(f"line {curLine} ends in \\r\\n")
ok = False
if line.find(b"\t") != -1:
print(f"line {curLine} contains \\t")
ok = False
if line.find(b"http") == -1 and len(line.rstrip(b"\r\n")) > 79:
print(f"line {curLine} exceeds maximum line length of 79")
ok = False
if ok:
print("All lines good")
good += 1
else:
bad += 1
print()
print(len(filenames), "file(s) checked")
print(good, "good")
print(bad, "with errors")
sys.exit(bad != 0)
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import java.io.*
import java.math.*
import java.util.*
class Reader {
private val In: BufferedReader
private var st: StringTokenizer? = null
constructor(inputStream: InputStream) {
In = BufferedReader(InputStreamReader(inputStream))
}
constructor(fileName: String) {
In = BufferedReader(FileReader(fileName))
}
fun next(): String {
while (st == null || !st!!.hasMoreTokens())
st = StringTokenizer(In.readLine().trim())
return st!!.nextToken()
}
fun nextLine(): String {
st = null
return In.readLine()
}
fun nextChar(): Char = next()[0]
fun nextDouble(): Double = next().toDouble()
fun nextInt(): Int = next().toInt()
fun nextLong(): Long = next().toLong()
fun close(): Unit = In.close()
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import java.io.*
import java.math.*
import java.util.*
class FastReader {
private val BUFFER_SIZE: Int = 1 shl 12
private var LENGTH: Int = -1
private val din: DataInputStream
private val buffer: ByteArray = ByteArray(BUFFER_SIZE)
private var bufferPointer: Int = 0
private var bytesRead: Int = 0
private var buf: CharArray = CharArray(0)
constructor(inputStream: InputStream) {
din = DataInputStream(inputStream)
}
constructor(fileName: String) {
din = DataInputStream(FileInputStream(fileName))
}
fun nextInt(): Int {
var ret: Int = 0
var c: Byte
do {
c = read()
} while (c <= 32)
var neg: Boolean = c == 45.toByte()
if (neg) c = read()
do {
ret = ret * 10 + c - 48
c = read()
} while (c >= 48)
if (neg) return -ret
return ret
}
fun nextLong(): Long {
var ret: Long = 0L
var c: Byte
do {
c = read()
} while (c <= 32)
var neg: Boolean = c == 45.toByte()
if (neg) c = read()
do {
ret = ret * 10 + c - 48
c = read()
} while (c >= 48)
if (neg) return -ret
return ret
}
fun nextDouble(): Double {
var ret: Double = 0.0
var div: Double = 1.0
var c: Byte
do {
c = read()
} while (c <= 32)
var neg: Boolean = c == 45.toByte()
if (neg) c = read()
do {
ret = ret * 10 + c - 48
c = read()
} while (c >= 48)
if (c == 46.toByte()) {
c = read()
while (c >= 48) {
div *= 10
ret += (c - 48) / div
c = read()
}
}
if (neg) return -ret
return ret
}
fun nextChar(): Char {
var c: Byte
do {
c = read()
} while (c <= 32)
return c.toChar()
}
fun next(): String {
var c: Byte
var cnt: Int = 0
do {
c = read()
} while (c <= 32)
do {
buf[cnt++] = c.toChar()
c = read()
} while (c > 32)
return String(buf, 0, cnt)
}
fun nextLine(): String {
while (bufferPointer > 0 && buffer[bufferPointer - 1] == 13.toByte())
read()
var c: Byte
var cnt: Int = 0
c = read()
while (c != 10.toByte() && c != 0.toByte()) {
if (c != 13.toByte()) buf[cnt++] = c.toChar()
c = read()
}
return String(buf, 0, cnt)
}
fun setLength(len: Int) {
LENGTH = len
buf = CharArray(len)
}
fun hasNext(): Boolean {
while (peek() > -1 && peek() <= 32) read()
return peek() > -1
}
fun hasNextLine(): Boolean {
while (peek() == 13.toByte()) read()
return peek() > -1
}
private fun fillBuffer() {
bufferPointer = 0
bytesRead = din.read(buffer, bufferPointer, BUFFER_SIZE)
if (bytesRead == -1) buffer[0] = -1
}
private fun read(): Byte {
if (bufferPointer == bytesRead) fillBuffer()
return buffer[bufferPointer++]
}
private fun peek(): Byte {
if (bufferPointer == bytesRead) fillBuffer()
return buffer[bufferPointer]
}
fun close() {
din.close()
}
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import java.io.*;
import java.math.*;
import java.util.*;
import java.awt.geom.*;
// Functions with polygons using the Area object
// Functions:
// makeArea(P): creates an Area from an array of points P
// union(areas): returns an Area that is the union of the Area
// objects in areas
// intersection(areas): returns an Area that is the intersection of the Area
// objects in areas
// getArea(area): returns the area of the Area object area
// Tested:
// https://open.kattis.com/problems/abstractart
// https://codeforces.com/problemset/gymProblem/100952/J
public class Polygon {
public static Area makeArea(double[][] P) {
Path2D.Double path = new Path2D.Double();
path.moveTo(P[0][0], P[0][1]);
for (int i = 1; i < P.length; i++) path.lineTo(P[i][0], P[i][1]);
path.closePath();
return new Area(path);
}
public static Area union(Area[] areas) {
Area ret = new Area(); for (Area area : areas) ret.add(area);
return ret;
}
public static Area intersection(Area[] areas) {
if (areas.length == 0) return new Area();
Area ret = areas[0];
for (int i = 1; i < areas.length; i++) ret.intersect(areas[i]);
return ret;
}
public static double getArea(Area area) {
PathIterator iter = area.getPathIterator(null); double ret = 0;
double[] buf = new double[6]; ArrayList<double[]> P = new ArrayList<>();
for (; !iter.isDone(); iter.next()) {
switch (iter.currentSegment(buf)) {
case PathIterator.SEG_MOVETO:
case PathIterator.SEG_LINETO:
P.add(new double[]{buf[0], buf[1]}); break;
case PathIterator.SEG_CLOSE:
for (int i = 0; i < P.size(); i++) {
double[] a = P.get(i), b = P.get((i + 1) % P.size());
ret -= a[0] * b[1] - a[1] * b[0];
}
P = new ArrayList<>(); break;
}
}
return ret / 2;
}
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import java.io.*;
import java.math.*;
import java.util.*;
public class FastReader {
private final int BUFFER_SIZE = 1 << 16; private int LENGTH = -1;
private DataInputStream din; private byte[] buffer, buf;
private int bufferPointer, bytesRead;
public FastReader(InputStream inputStream) {
din = new DataInputStream(inputStream); buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String fileName) throws IOException {
din = new DataInputStream(new FileInputStream(fileName));
buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0;
}
public int nextInt() throws IOException {
int ret = 0; byte c; do {
c = read();
} while (c <= ' ');
boolean neg = (c == '-'); if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0; byte c; do {
c = read();
} while (c <= ' ');
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1; byte c; do {
c = read();
} while (c <= ' ');
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0');
if (c == '.') while ((c = read()) >= '0') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
public char nextChar() throws IOException {
byte c; do {
c = read();
} while (c <= ' ');
return (char) c;
}
public String next() throws IOException {
int cnt = 0; byte c; do {
c = read();
} while (c <= ' ');
do {
buf[cnt++] = c;
} while ((c = read()) > ' ');
return new String(buf, 0, cnt);
}
public String nextLine() throws IOException {
while (bufferPointer > 0 && buffer[bufferPointer - 1] == '\r') read();
int cnt = 0; byte c;
while ((c = read()) != '\n' && c != '\0') if (c != '\r') buf[cnt++] = c;
return new String(buf, 0, cnt);
}
public void setLength(int len) { LENGTH = len; buf = new byte[len]; }
public boolean hasNext() throws IOException {
while (peek() != -1 && peek() <= ' ') read();
return peek() != -1;
}
public boolean hasNextLine() throws IOException {
while (peek() == '\r') read();
return peek() != -1;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
private byte peek() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
public class Pair<Item1 extends Comparable<Item1>,
Item2 extends Comparable<Item2>>
implements Comparable<Pair<Item1, Item2>> {
public Item1 first;
public Item2 second;
public Pair(Item1 first, Item2 second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
return 31 * first.hashCode() + second.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair p = (Pair) o;
return p.first.equals(first) && p.second.equals(second);
}
@Override
public int compareTo(Pair<Item1, Item2> p) {
int o = first.compareTo(p.first);
return o == 0 ? second.compareTo(p.second) : o;
}
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
import java.io.*;
import java.math.*;
import java.util.*;
public class Reader {
private BufferedReader in; private StringTokenizer st;
public Reader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
}
public Reader(String fileName) throws FileNotFoundException {
in = new BufferedReader(new FileReader(fileName));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine().trim());
return st.nextToken();
}
public String nextLine() throws IOException {
st = null; return in.readLine();
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public byte nextByte() throws IOException {
return Byte.parseByte(next());
}
public char nextChar() throws IOException { return next().charAt(0); }
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public float nextFloat() throws IOException {
return Float.parseFloat(next());
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
public void close() throws IOException { in.close(); }
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Cuthill-McKee reordering of a graph to reduce the bandwith
// Vertices are 0-indexed
// Constructor Arguments:
// G: a generic undirected graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the graph
// rev: a boolean indicating whether the order should be reversed or not,
// performs better with Gaussian Elimination
// Fields:
// mapping: a mapping from the original vertex to the reordered vertex
// revMapping: a mapping from the reordered vertex to the original vertex
// In practice, has a small constant
// Time Complexity:
// constructor: O(V log V + E log E)
// Memory Complexity: O(V)
// Tested:
// https://dmoj.ca/problem/ddrp3
struct CuthillMcKee {
int V; vector<int> mapping, revMapping, deg;
template <class Graph> CuthillMcKee(const Graph &G, bool rev = false)
: V(G.size()), mapping(V, 0), revMapping(V), deg(V, 0) {
for (int v = 0; v < V; v++) for (int w : G[v]) { deg[v]++; deg[w]++; }
auto cmpDeg = [&] (int v, int w) {
return make_pair(deg[v], v) < make_pair(deg[w], w);
};
int front = 0, back = 0; vector<int> P(V); iota(P.begin(), P.end(), 0);
sort(P.begin(), P.end(), cmpDeg); for (int i = 0; i < V; i++) {
int s = P[i]; if (mapping[s]) continue;
mapping[revMapping[back++] = s] = 1; while (front < back) {
int v = revMapping[front++]; vector<int> adj; adj.reserve(deg[v]);
for (int w : G[v]) adj.push_back(w);
sort(adj.begin(), adj.end(), cmpDeg);
for (int w : adj) if (!mapping[w]) mapping[revMapping[back++] = w] = 1;
}
}
if (rev) reverse(revMapping.begin(), revMapping.end());
for (int i = 0; i < V; i++) mapping[revMapping[i]] = i;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Breadth First Traversal of a graph (weighted or unweighted)
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the graph
// Constructor Arguments:
// G: a generic graph structure (weighted or unweighted)
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints for an unweighted graph, or a list of
// pair<int, T> for a weighted graph with weights of type T)
// size() const: returns the number of vertices in the graph
// s: a single source vertex
// src: a vector of source vertices
// INF: a value for infinity
// Fields:
// dist: vector of distance from the closest source vertex to each vertex,
// or INF if unreachable, and is also the shortest distance for
// an unweighted graph
// par: the parent vertex for each vertex in the breadth first search tree,
// or -1 if there is no parent
// Functions:
// getPath(v): returns the list of directed edges on the path from the
// closest source vertex to vertex v
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// getPath: O(V)
// Memory Complexity: O(V)
// Tested:
// https://www.spoj.com/problems/BITMAP/
// https://dmoj.ca/problem/ddrp3
template <class T = int> struct BFS {
using Edge = tuple<int, int, T>; vector<T> dist; vector<int> par; T INF;
int getTo(int e) { return e; }
T getWeight(int) { return 1; }
int getTo(const pair<int, T> &e) { return e.first; }
T getWeight(const pair<int, T> &e) { return e.second; }
template <class Graph> BFS(const Graph &G, const vector<int> &srcs,
T INF = numeric_limits<T>::max())
: dist(G.size(), INF), par(G.size(), -1), INF(INF) {
vector<int> q(G.size()); int front = 0, back = 0;
for (int s : srcs) dist[q[back++] = s] = T();
while (front < back) {
int v = q[front++]; for (auto &&e : G[v]) {
int w = getTo(e); if (dist[w] >= INF)
dist[q[back++] = w] = dist[par[w] = v] + getWeight(e);
}
}
}
template <class Graph> BFS(const Graph &G, int s,
T INF = numeric_limits<T>::max())
: BFS(G, vector<int>{s}, INF) {}
vector<Edge> getPath(int v) {
vector<Edge> path; for (; par[v] != -1; v = par[v])
path.emplace_back(par[v], v, dist[v] - dist[par[v]]);
reverse(path.begin(), path.end()); return path;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Multidirectional breadth first search of an undirected, unweighted graph to
// query for the closest distance between two distinct vertices in a set
// of vertices
// Vertices are 0-indexed
// Template Arguments:
// Graph: a generic undirected graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// which is a list of ints
// size() const: returns the number of vertices in the graph
// Constructor Arguments:
// G: a instance of Graph
// Functions:
// closest(src): returns the closest distance between any two distinct
// vertices in src
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// closest: O(V + E) worst case, much better in practice if two source
// vertices are connected and the graph is random and sparse
// Memory Complexity: O(V)
// Tested:
// https://dmoj.ca/problem/acc1p2
// https://dmoj.ca/problem/wac1p6
template <class Graph> struct MultidirectionalBFS {
Graph G; vector<int> d, from, vis, q; int stamp;
MultidirectionalBFS(const Graph &G)
: G(G), d(G.size(), INT_MAX), from(G.size(), -1), vis(G.size(), 0),
q(G.size()), stamp(0) {}
int closest(const vector<int> &srcs) {
assert(int(srcs.size()) >= 2);
int front = 0, back = 0; ++stamp; for (int s : srcs) {
if (vis[s] == stamp) return 0;
vis[q[back++] = from[s] = s] = stamp; d[s] = 0;
}
int mn = INT_MAX; while (front < back) {
int v = q[front++]; for (int w : G[v]) {
if (vis[v] != vis[w]) {
d[q[back++] = w] = d[v] + 1; vis[w] = vis[v]; from[w] = from[v];
} else if (from[v] != from[w]) {
int sm = d[v] + d[w] + 1; if (sm > mn) return mn;
mn = sm;
}
}
}
return mn;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Computes the Transitive Closure in a graph using Floyd Warshall
// with bitset optimizations
// Template Arguments:
// MAXV: the maximum number of vertices in the graph
// Constructor Arguments:
// matrix: a V x V matrix (represented by V bitsets of size MAXV) such that
// matrix[v][w] is 1 if there is a directed edge from v to w and
// 0 otherwise
// Functions:
// reachable(v, w): returns true if w is reachable from v and false otherwise
// In practice, has a very small constant, slower than the SCC variant
// Time Complexity:
// constructor: O(V^3 / 64)
// reachable: O(1)
// Memory Complexity: O(MAXV V / 64)
// Tested:
// Stress Tested
// https://dmoj.ca/problem/acc2p2
// https://open.kattis.com/problems/watchyourstep
template <const int MAXV> struct TransitiveClosureFloydWarshall {
vector<bitset<MAXV>> dp;
TransitiveClosureFloydWarshall(vector<bitset<MAXV>> matrix)
: dp(move(matrix)) {
int V = dp.size(); for (int v = 0; v < V; v++) dp[v][v] = 1;
for (int u = 0; u < V; u++) for (int v = 0; v < V; v++)
if (dp[v][u]) dp[v] |= dp[u];
}
bool reachable(int v, int w) { return dp[v][w]; }
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Maintains the Transitive Closure in a graph after edges are added
// Constructor Arguments:
// V: the number of vertices in the graph
// Functions:
// reachable(v, w): returns true if w is reachable from v and false otherwise
// addEdge(v, w): adds an edge between vertices v and w, returns true if the
// resulting edge does not create a new cycle and false otherwise
// In practice, has a small constant
// Time Complexity:
// constructor: O(V^2)
// reachable: O(1)
// addEdge: O(V) amortized
// Memory Complexity: O(V^2)
// Tested:
// https://www.spoj.com/problems/GHOSTS/
struct IncrementalTransitiveClosure {
int V; vector<vector<int>> par; vector<vector<vector<int>>> ch;
IncrementalTransitiveClosure(int V)
: V(V), par(V, vector<int>(V, -1)), ch(V, vector<vector<int>>(V)) {}
bool reachable(int v, int w) { return v == w || par[v][w] >= 0; }
void meld(int root, int sub, int v, int w) {
par[root][w] = v; ch[root][v].push_back(w);
for (int c : ch[sub][w]) if (!reachable(root, c)) meld(root, sub, w, c);
}
bool addEdge(int v, int w) {
if (reachable(w, v)) return false;
if (reachable(v, w)) return true;
for (int u = 0; u < V; u++) if (reachable(u, v) && !reachable(u, w))
meld(u, w, v, w);
return true;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Computes the Topological Order of a directed acyclic graph
// Vertices are 0-indexed
// Constructor Arguments:
// G: a generic directed acyclic graph structure
// which can be weighted or unweighted, though weights do not change
// the topological order
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints for an unweighted graph, or a list of
// pair<int, T> for a weighted graph with weights of type T)
// size() const: returns the number of vertices in the graph
// Fields:
// ind: a vector of the topological order index for each vertex
// ord: a vector of the vertices sorted by topological order index
// In practice, has a moderate constant, faster than DepthFirstOrder
// Time Complexity:
// constructor: O(V + E)
// Memory Complexity: O(V)
// Tested:
// https://atcoder.jp/contests/dp/tasks/dp_g
struct TopologicalOrder {
int V; vector<int> ind, ord, inDeg;
int getTo(int e) { return e; }
template <class T> int getTo(const pair<int, T> &e) { return e.first; }
template <class DAG> TopologicalOrder(const DAG &G)
: V(G.size()), ind(V, -1), ord(V), inDeg(V, 0) {
int front = 0, back = 0;
for (int v = 0; v < V; v++) for (auto &&e : G[v]) inDeg[getTo(e)]++;
for (int v = 0; v < V; v++) if (inDeg[v] == 0) ord[back++] = v;
while (front < back) {
int v = ord[front]; ind[v] = front++;
for (auto &&e : G[v]) if (--inDeg[getTo(e)] == 0) ord[back++] = getTo(e);
}
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "../components/StronglyConnectedComponents.h"
using namespace std;
// Computes the Transitive Closure in a graph using strongly connected
// components and dynamic programming with bitset optimizations
// Template Arguments:
// MAXV: the maximum number of vertices in the graph
// Constructor Arguments:
// G: a generic graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the graph
// Functions:
// reachable(v, w): returns true if w is reachable from v and false otherwise
// In practice, has a very small constant, faster than the
// Floyd Warshall variant
// Time Complexity:
// constructor: O(V + E + MAXV E / 64)
// reachable: O(1)
// Memory Complexity: O(V + E + MAXV V / 64)
// Tested:
// Stress Tested
// https://dmoj.ca/problem/acc2p2
// https://open.kattis.com/problems/watchyourstep
template <const int MAXV> struct TransitiveClosureSCC {
vector<pair<int, int>> DAG; SCC scc; vector<bitset<MAXV>> dp;
template <class Graph> TransitiveClosureSCC(const Graph &G)
: DAG(), scc(G, DAG), dp(scc.components.size()) {
for (int i = 0; i < int(dp.size()); i++) dp[i][i] = 1;
for (auto &&e : DAG) dp[e.first] |= dp[e.second];
}
bool reachable(int v, int w) { return dp[scc.id[v]][scc.id[w]]; }
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Finds the centroids for each connected component in a forest
// Vertices are 0-indexed
// Function Arguments:
// G: a generic forest structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the forest
// Return Value: a vector of vectors of integers containing the centroids for
// each connected component with each connected component having either one
// or two centroids; connected components are ordered by their minimum vertex
// In practice, has a moderate constant
// Time Complexity: O(V)
// Memory Complexity: O(V)
// Tested:
// https://codeforces.com/contest/1406/problem/C
template <class Forest> vector<vector<int>> getCentroids(const Forest &G) {
int V = G.size(); vector<int> size(V, 0); vector<vector<int>> centroids;
function<int(int, int)> getSize = [&] (int v, int prev) {
size[v] = 1; for (int w : G[v]) if (w != prev) size[v] += getSize(w, v);
return size[v];
};
function<void(int, int, int)> dfs = [&] (int v, int prev, int compSize) {
bool b = true; for (int w : G[v])
if (w != prev) { dfs(w, v, compSize); b &= size[w] <= compSize / 2; }
if (b && compSize - size[v] <= compSize / 2) centroids.back().push_back(v);
};
for (int v = 0; v < V; v++)
if (size[v] == 0) { centroids.emplace_back(); dfs(v, -1, getSize(v, -1)); }
return centroids;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "BreadthFirstSearch.h"
using namespace std;
// Computes the diameter of a undirected tree (weighted or unweighted)
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the tree
// Constructor Arguments:
// G: a generic undirected tree structure (weighted or unweighted)
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints for an unweighted tree, or a list of
// pair<int, T> for a weighted tree with weights of type T)
// size() const: returns the number of vertices in the tree
// INF: a value for infinity
// Fields:
// endpoints: a pair containing the vertices on the endpoints of the diameter
// diameter: the length of the diameter
// Functions:
// getPath(): returns the list of edges on the diameter
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V)
// getPath: O(V)
// Memory Complexity: O(V)
// Tested:
// https://judge.yosupo.jp/problem/tree_diameter
template <class T = int> struct TreeDiameter {
BFS<T> bfs; pair<int, int> endpoints; T diameter;
template <class Tree>
TreeDiameter(const Tree &G, T INF = numeric_limits<T>::max())
: bfs(G, 0, INF) {
endpoints.first = max_element(bfs.dist.begin(), bfs.dist.end())
- bfs.dist.begin();
move(bfs); bfs = BFS<T>(G, endpoints.first);
endpoints.second = max_element(bfs.dist.begin(), bfs.dist.end())
- bfs.dist.begin();
diameter = bfs.dist[endpoints.second];
}
vector<typename BFS<T>::Edge> getPath() {
return bfs.getPath(endpoints.second);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Bidirectional breadth first search of an undirected, unweighted graph to
// query for the distance between two vertices
// Vertices are 0-indexed
// Template Arguments:
// Graph: a generic undirected graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// which is a list of ints
// size() const: returns the number of vertices in the graph
// Constructor Arguments:
// G: a instance of Graph
// Functions:
// dist(s, t): returns the distance between vertices s and t
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// dist: O(V + E) worst case, much better in practice if s and t are
// connected and the graph is random and sparse
// Memory Complexity: O(V)
// Tested:
// https://dmoj.ca/problem/acc1p2
template <class Graph> struct BidirectionalBFS {
Graph G; vector<int> d, vis, q; int stamp;
BidirectionalBFS(const Graph &G)
: G(G), d(G.size(), INT_MAX), vis(G.size(), 0), q(G.size()), stamp(0) {}
int dist(int s, int t) {
if (s == t) return 0;
int front = 0, back = 0; d[s] = d[t] = 0;
vis[q[back++] = s] = ++stamp; vis[q[back++] = t] = -stamp;
while (front < back) {
int v = q[front++]; for (int w : G[v]) {
if (vis[v] == -vis[w]) return d[v] + d[w] + 1;
else if (vis[v] != vis[w]) {
d[q[back++] = w] = d[v] + 1; vis[w] = vis[v];
}
}
}
return INT_MAX;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Breadth First Traversal of a graph where all edge weights are 0 or 1
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the graph
// Constructor Arguments:
// G: a generic weighted graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of pair<int, T> with weights of type T)
// size() const: returns the number of vertices in the graph
// s: a single source vertex
// src: a vector of source vertices
// Fields:
// dist: vector of the shortest distance from the closest source vertex to
// each vertex, or INT_MAX if unreachable
// par: the parent vertex for each vertex in the breadth first search tree,
// or -1 if there is no parent
// Functions:
// getPath(v): returns the list of directed edges on the path from the
// closest source vertex to vertex v
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// getPath: O(V)
// Memory Complexity: O(V)
// Tested:
// https://www.codechef.com/problems/REVERSE
// https://atcoder.jp/contests/abc176/tasks/abc176_d
struct ZeroOneBFS {
using Edge = tuple<int, int, int>; vector<int> dist, par;
template <class WeightedGraph>
ZeroOneBFS(const WeightedGraph &G, const vector<int> &srcs)
: dist(G.size(), INT_MAX), par(G.size(), -1) {
vector<int> q(G.size()), stk(G.size()); int front = 0, back = 0, top = 0;
for (int s : srcs) dist[stk[top++] = s] = 0;
while (top > 0 || front < back) {
int v = top > 0 ? stk[--top] : q[front++]; for (auto &&e : G[v]) {
int w = e.first; if (dist[w] > dist[v] + e.second) {
(e.second == 0 ? stk[top++] : q[back++]) = w;
dist[w] = dist[par[w] = v] + e.second;
}
}
}
}
template <class WeightedGraph> ZeroOneBFS(const WeightedGraph &G, int s)
: ZeroOneBFS(G, vector<int>{s}) {}
vector<Edge> getPath(int v) {
vector<Edge> path; for (; par[v] != -1; v = par[v])
path.emplace_back(par[v], v, dist[v] - dist[par[v]]);
reverse(path.begin(), path.end()); return path;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Computes Depth First Orders of a graph (pre order, post order,
// topological/reverse post order)
// Vertices are 0-indexed
// Constructor Arguments:
// G: a generic graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the graph
// rt: a single root vertex
// roots: a vector of root vertices for each connected component
// Fields:
// preInd: a vector of the pre order index for each vertex
// postInd: a vector of the post order index for each vertex
// revPostInd: a vector of the topological/reverse post order index
// for each vertex
// preVert: a vector of the vertices sorted by pre order index
// postVert: a vector of the vertices sorted by post order index
// revPostVert: a vector of the vertices sorted by topological/reverse post
// order index
// In practice, has a moderate constant, slower than TopologicalOrder
// Time Complexity:
// constructor: O(V + E)
// Memory Complexity: O(V)
// Tested:
// https://atcoder.jp/contests/nikkei2019-qual/tasks/nikkei2019_qual_d
// https://codeforces.com/contest/24/problem/A
struct DFSOrder {
int V, curPre, curPost, curRevPost;
vector<int> preInd, postInd, revPostInd, preVert, postVert, revPostVert;
template <class Graph> void dfs(const Graph &G, int v) {
preVert[preInd[v] = curPre++] = v;
for (int w : G[v]) if (preInd[w] == -1) dfs(G, w);
postVert[postInd[v] = curPost++] = v;
revPostVert[revPostInd[v] = curRevPost--] = v;
}
template <class Graph>
DFSOrder(const Graph &G, const vector<int> &roots = vector<int>())
: V(G.size()), curPre(0), curPost(0), curRevPost(V - 1), preInd(V, -1),
postInd(V), revPostInd(V), preVert(V), postVert(V), revPostVert(V) {
if (roots.empty()) {
for (int v = 0; v < V; v++) if (preInd[v] == -1) dfs(G, v);
} else for (int v : roots) if (preInd[v] == -1) dfs(G, v);
}
template <class Graph> DFSOrder(const Graph &G, int rt)
: DFSOrder(G, vector<int>{rt}) {}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include <ext/pb_ds/priority_queue.hpp>
using namespace std;
using namespace __gnu_pbds;
// Computes the maximum flow using a path with the minimum cost by finding
// Shortest Augmenting Paths
// Can handle negative edges but not negative cost cycles
// (assertion failure if there is a negative cost cycle)
// Vertices are 0-indexed
// Template Arguments:
// FlowUnit: the type of the flow
// CostUnit: the type of the cost, must be integral
// Constructor Arguments:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// COST_INF: a value for the cost infinity
// Fields:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// COST_INF: a value for the cost infinity
// G: an adjacency list of all edges and reverse edges in the flow network
// Functions:
// addEdge(v, w, vwCap, vwCost): adds an edge from v to w with capacity
// vwCap and cost vwCost
// getFlowMinCost(s, t): returns the maximum flow from s to t with
// the minimum cost
// In practice, has a very small constant
// Time Complexity:
// constructor: O(V)
// addEdge: O(1)
// getFlowMinCost: O(E^2 V log V), much faster in practice
// Memory Complexity: O(V + E)
// Tested:
// https://open.kattis.com/problems/mincostmaxflow
// https://loj.ac/p/102
// https://www.spoj.com/problems/SCITIES/
// https://dmoj.ca/problem/tle17c7p5
template <class FlowUnit, class CostUnit> struct SAPMinCostMaxFlow {
struct Edge {
int to, rev; FlowUnit cap, resCap; CostUnit cost;
Edge(int to, int rev, FlowUnit cap, CostUnit cost)
: to(to), rev(rev), cap(cap), resCap(cap), cost(cost) {}
};
struct Node {
CostUnit d; int v; Node(CostUnit d, int v) : d(d), v(v) {}
bool operator < (const Node &o) const { return d > o.d; }
};
int V; FlowUnit FLOW_EPS; CostUnit COST_INF; vector<vector<Edge>> G;
bool hasNegativeCost; vector<CostUnit> phi, dist;
vector<Edge*> to; vector<int> par;
SAPMinCostMaxFlow(int V, FlowUnit FLOW_EPS = FlowUnit(1e-9),
CostUnit COST_INF = numeric_limits<CostUnit>::max())
: V(V), FLOW_EPS(FLOW_EPS), COST_INF(COST_INF), G(V),
hasNegativeCost(false), phi(V), dist(V), to(V), par(V) {}
void addEdge(int v, int w, FlowUnit vwCap, CostUnit vwCost) {
if (v == w) return;
if (vwCost < CostUnit()) hasNegativeCost = true;
G[v].emplace_back(w, int(G[w].size()), vwCap, vwCost);
G[w].emplace_back(v, int(G[v].size()) - 1, FlowUnit(), -vwCost);
}
void bellmanFord(int s) {
fill(phi.begin(), phi.end(), COST_INF); phi[s] = CostUnit();
for (int j = 0; j < V - 1; j++) for (int v = 0; v < V; v++)
for (auto &&e : G[v]) if (e.resCap > FLOW_EPS && phi[v] < COST_INF)
phi[e.to] = min(phi[e.to], phi[v] + e.cost);
for (int v = 0; v < V; v++) for (auto &&e : G[v])
if (e.resCap > FLOW_EPS && phi[v] < COST_INF)
assert(phi[e.to] <= phi[v] + e.cost);
}
bool dijkstra(int s, int t) {
fill(dist.begin(), dist.end(), COST_INF); fill(par.begin(), par.end(), -1);
vector<bool> seen(V, false); __gnu_pbds::priority_queue<Node> PQ;
vector<typename decltype(PQ)::point_iterator> ptr(V, PQ.end());
ptr[s] = PQ.push(Node(dist[s] = CostUnit(), s)); while (!PQ.empty()) {
int v = PQ.top().v; PQ.pop(); ptr[v] = PQ.end(); seen[v] = true;
for (auto &&e : G[v]) {
int w = e.to; if (seen[w] || e.resCap <= FLOW_EPS) continue;
CostUnit d = dist[v] + e.cost + phi[v] - phi[w];
if (dist[w] <= d) continue;
par[w] = v; to[w] = &e;
if (ptr[w] == PQ.end()) ptr[w] = PQ.push(Node(dist[w] = d, w));
else PQ.modify(ptr[w], Node(dist[w] = d, w));
}
}
return dist[t] < COST_INF;
}
pair<FlowUnit, CostUnit> getFlowMinCost(int s, int t) {
pair<FlowUnit, CostUnit> ret = make_pair(FlowUnit(), CostUnit());
fill(phi.begin(), phi.end(), CostUnit()); if (s == t) return ret;
if (hasNegativeCost) bellmanFord(s);
while (dijkstra(s, t)) {
FlowUnit aug = FlowUnit(); for (int v = t; par[v] != -1; v = par[v])
if (v == t || aug > to[v]->resCap) aug = to[v]->resCap;
ret.first += aug; for (int v = t; par[v] != -1; v = par[v]) {
to[v]->resCap -= aug; G[to[v]->to][to[v]->rev].resCap += aug;
ret.second += aug * to[v]->cost;
}
for (int v = 0; v < V; v++) if (dist[v] < COST_INF) phi[v] += dist[v];
}
return ret;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "PushRelabelMaxFlow.h"
using namespace std;
// Given a list of weighted edges representing an undirected flow graph,
// compute a tree such that the max flow/min cut between any pair of vertices
// is given by the minimum weight edge between the two vertices
// Template Arguments:
// T: the type of the weight of the edges
// Constructor Arguments:
// V: number of vertices in the graph
// edges: a vector of tuples in the form (v, w, weight) representing
// an undirected edge in the graph between vertices v and w with
// weight of weight
// Fields:
// treeEdges: a vector of tuples of the edges in the Gomory-Hu Tree
// In practice, has a very small constant
// Time Complexity:
// constructor: O(V^3 sqrt E), much faster in practice
// Memory Complexity: O(V + E)
// Tested:
// https://codeforces.com/gym/101480/problem/J
template <class T> struct GomoryHu {
using Edge = tuple<int, int, T>; vector<Edge> treeEdges;
GomoryHu(int V, const vector<Edge> &edges, T EPS = T(1e-9)) {
PushRelabelMaxFlow<FlowEdge<T>> mf(V, EPS); for (auto &&e : edges)
mf.addEdge(get<0>(e), get<1>(e), get<2>(e), get<2>(e));
vector<int> par(V, 0); for (int i = 1; i < V; i++) {
for (int v = 0; v < V; v++) for (auto &&e : mf.G[v]) e.resCap = e.cap;
treeEdges.emplace_back(i, par[i], mf.getFlow(i, par[i]));
for (int j = i + 1; j < V; j++)
if (par[j] == par[i] && mf.cut[j]) par[j] = i;
}
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// A sample edge struct for maximum flow
// Flow of edge can be found with cap - resCap
// Template Arguments:
// _FlowUnit: the type of the flow
// Constructor Arguments:
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// cap: the initial capacity of this edge
// Fields:
// FlowUnit: the type of the flow
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// cap: the initial capacity of this edge
// resCap: the residual capacity of this edge
// Tested:
// https://open.kattis.com/problems/maxflow
// https://open.kattis.com/problems/mincut
// https://www.spoj.com/problems/FASTFLOW/
// https://vn.spoj.com/problems/FFLOW/
// https://loj.ac/p/127
template <class _FlowUnit> struct FlowEdge {
using FlowUnit = _FlowUnit; int to, rev; FlowUnit cap, resCap;
FlowEdge(int to, int rev, FlowUnit cap)
: to(to), rev(rev), cap(cap), resCap(cap) {}
};
// Computes the maximum flow and minimum cut in a flow network using the
// Push Relabel algorithm with the highest label selection rule and
// gap relabelling heuristic
// Vertices are 0-indexed
// Template Arguments:
// Edge: a generic edge class (such as FlowEdge)
// Required Fields:
// FlowUnit: the type of the flow
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// resCap: the residual capacity of this edge
// Required Functions:
// constructor(to, rev, cap): initializes the edge to vertex to with
// the reverse index rev and capacity cap
// Constructor Arguments:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// Fields:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// G: an adjacency list of all edges and reverse edges in the flow network
// cut: a vector of booleans indicating which side of a minimum s-t cut it
// is on (true if on the same side as s, false if on the same side as t)
// Functions:
// addEdge(v, w, vwCap, wvCap): adds an edge from v to w with capacity
// vwCap and a reverse capacity of wvCap
// getFlow(s, t): returns the maximum flow from s to t as well as the minimum
// s-t cut
// In practice, has a very small constant
// Time Complexity:
// constructor: O(V)
// addEdge: O(1)
// getFlow: O(V^2 sqrt E), much faster in practice
// Memory Complexity: O(V + E)
// Tested:
// https://open.kattis.com/problems/maxflow
// https://open.kattis.com/problems/mincut
// https://www.spoj.com/problems/FASTFLOW/
// https://vn.spoj.com/problems/FFLOW/
// https://loj.ac/p/127
template <class Edge> struct PushRelabelMaxFlow {
using FlowUnit = typename Edge::FlowUnit;
int V; FlowUnit FLOW_EPS; vector<vector<Edge>> G; vector<bool> cut;
PushRelabelMaxFlow(int V, FlowUnit FLOW_EPS = FlowUnit(1e-9))
: V(V), FLOW_EPS(FLOW_EPS), G(V) {}
void addEdge(int v, int w, FlowUnit vwCap, FlowUnit wvCap = FlowUnit()) {
if (v == w) return;
G[v].emplace_back(w, int(G[w].size()), vwCap);
G[w].emplace_back(v, int(G[v].size()) - 1, wvCap);
}
FlowUnit getFlow(int s, int t) {
cut.assign(V, false); if (s == t) return FlowUnit();
vector<FlowUnit> ex(V, FlowUnit()); vector<int> h(V, 0), cnt(V * 2, 0);
vector<vector<int>> hs(V * 2);
vector<typename vector<Edge>::iterator> cur(V);
auto push = [&] (int v, Edge &e, FlowUnit df) {
int w = e.to;
if (abs(ex[w]) <= FLOW_EPS && df > FLOW_EPS) hs[h[w]].push_back(w);
e.resCap -= df; G[w][e.rev].resCap += df; ex[v] -= df; ex[w] += df;
};
h[s] = V; ex[t] = FlowUnit(1); cnt[0] = V - 1;
for (int v = 0; v < V; v++) cur[v] = G[v].begin();
for (auto &&e : G[s]) push(s, e, e.resCap);
if (!hs[0].empty()) for (int hi = 0; hi >= 0;) {
int v = hs[hi].back(); hs[hi].pop_back(); while (ex[v] > FLOW_EPS) {
if (cur[v] == G[v].end()) {
h[v] = INT_MAX; for (auto e = G[v].begin(); e != G[v].end(); e++)
if (e->resCap > FLOW_EPS && h[v] > h[e->to] + 1)
h[v] = h[(cur[v] = e)->to] + 1;
cnt[h[v]]++;
if (--cnt[hi] == 0 && hi < V) for (int w = 0; w < V; w++)
if (hi < h[w] && h[w] < V) { cnt[h[w]]--; h[w] = V + 1; }
hi = h[v];
} else if (cur[v]->resCap > FLOW_EPS && h[v] == h[cur[v]->to] + 1) {
push(v, *cur[v], min(ex[v], cur[v]->resCap));
} else cur[v]++;
}
while (hi >= 0 && hs[hi].empty()) hi--;
}
for (int v = 0; v < V; v++) cut[v] = h[v] >= V;
return -ex[s];
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "PushRelabelMaxFlow.h"
using namespace std;
// A sample edge struct for flow with demands
// Flow of edge can be found with cap - resCap
// Template Arguments:
// _FlowUnit: the type of the flow
// Constructor Arguments:
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// dem: the initial demand of this edge
// cap: the initial capacity of this edge
// Fields:
// FlowUnit: the type of the flow
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// dem: the initial demand of this edge
// cap: the initial capacity of this edge
// resCap: the residual capacity of this edge
// Tested:
// https://loj.ac/p/117
// https://dmoj.ca/problem/wac4p6
// https://codeforces.com/gym/100199/problem/B
template <class _FlowUnit> struct FlowEdgeDemands {
using FlowUnit = _FlowUnit; int to, rev; FlowUnit dem, cap, resCap;
FlowEdgeDemands(int to, int rev, FlowUnit dem, FlowUnit cap)
: to(to), rev(rev), dem(dem), cap(cap), resCap(cap) {}
};
// Computes the minimum/feasible/maximum flow in a flow network with
// edge demands using the Push Relabel algorithm with the highest label
// selection rule and gap relabelling heuristic
// Vertices are 0-indexed
// Template Arguments:
// Edge: a generic edge class (such as FlowEdgeDemands)
// Required Fields:
// FlowUnit: the type of the flow
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// dem: the initial demand of this edge
// cap: the initial capacity of this edge
// resCap: the residual capacity of this edge
// Required Functions:
// constructor(to, rev, dem, cap): initializes the edge to vertex to with
// the reverse index rev, demand dem, and capacity cap
// Constructor Arguments:
// V: the number of vertices in the flow network
// FLOW_INF: a value for the flow infinity
// FLOW_EPS: a value for the flow epsilon
// Fields:
// V: the number of vertices in the flow network
// FLOW_INF: a value for the flow infinity
// FLOW_EPS: a value for the flow epsilon
// G: an adjacency list of all edges and reverse edges in the flow network
// Functions:
// addEdge(v, w, vwDem, wvCap): adds an edge from v to w with capacity
// vwCap and a demand of vwDem
// getFeasibleFlow(s, t, flowType): computes a feasible flow (or circulation
// if s and t are -1), maximizes the flow value if flowType is positive,
// minimizes it if flowType is negative, and finds any flow if 0; returns
// a pair of a boolean and FlowUnit indicating whether a flow is feasible
// and the flow value
// getMinFlow(s, t): returns a pair of a boolean and FlowUnit indicating
// whether a flow is feasible and the minimum flow value
// getMaxFlow(s, t): returns a pair of a boolean and FlowUnit indicating
// whether a flow is feasible and the maximum flow value
// In practice, has a very small constant
// Time Complexity:
// constructor: O(V)
// addEdge: O(1)
// getFeasibleFlow, getMinFlow, getMaxFlow: O(V^2 sqrt E),
// much faster in practice
// Memory Complexity: O(V + E)
// Tested:
// https://loj.ac/p/117
// https://dmoj.ca/problem/wac4p6
// https://codeforces.com/gym/100199/problem/B
template <class Edge>
struct PushRelabelFlowDemands : public PushRelabelMaxFlow<Edge> {
using MF = PushRelabelMaxFlow<Edge>;
using FlowUnit = typename Edge::FlowUnit; using MF::V; using MF::G;
FlowUnit FLOW_INF; vector<FlowUnit> outDem, inDem;
PushRelabelFlowDemands(
int V, FlowUnit FLOW_INF = numeric_limits<FlowUnit>::max(),
FlowUnit FLOW_EPS = FlowUnit(1e-9))
: MF(V, FLOW_EPS), FLOW_INF(FLOW_INF),
outDem(V, FlowUnit()), inDem(V, FlowUnit()) {}
void addEdge(int v, int w, FlowUnit vwDem, FlowUnit vwCap, int type = 1) {
if (v == w) return;
G[v].emplace_back(w, int(G[w].size()), vwDem, vwCap);
G[w].emplace_back(v, int(G[v].size()) - 1, -vwDem, -vwDem);
if (type == 1) { outDem[v] += vwDem; inDem[w] += vwDem; }
}
pair<bool, FlowUnit> getFeasibleFlow(int s = -1, int t = -1,
int flowType = 0) {
int ss = V, tt = V + 1; G.emplace_back(); G.emplace_back();
FlowUnit bnd = FLOW_INF, sm = 0;
pair<bool, FlowUnit> ret(true, flowType < 0 ? FLOW_INF : FlowUnit());
for (int v = 0; v < V; v++) {
for (auto &&e : G[v]) e.cap -= e.dem;
addEdge(ss, v, FlowUnit(), inDem[v], 2);
addEdge(v, tt, FlowUnit(), outDem[v], 2); sm += inDem[v];
}
for (int h = 0; h < 2; h++) {
for (int v = 0; v < V + 2; v++) for (auto &&e : G[v]) e.resCap = e.cap;
if (s != -1 && t != -1) addEdge(t, s, FlowUnit(), bnd, 2);
V += 2;
if (sm - (bnd = MF::getFlow(ss, tt)) > MF::FLOW_EPS) ret.first = false;
V -= 2; if (s != -1 && t != -1) {
G[s].pop_back();
if (ret.first) ret.second = G[t].back().cap - G[t].back().resCap;
G[t].pop_back();
}
if (flowType >= 0 || !ret.first || h > 0) break;
for (int v = 0; v < V + 2; v++) for (auto &&e : G[v]) e.resCap = e.cap;
V += 2; bnd -= MF::getFlow(ss, tt); V -= 2;
}
G.pop_back(); G.pop_back();
for (int v = 0; v < V; v++) {
G[v].pop_back(); G[v].pop_back(); for (auto &&e : G[v]) e.cap += e.dem;
}
if (flowType > 0 && ret.first) ret.second += MF::getFlow(s, t);
return ret;
}
pair<bool, FlowUnit> getMinFlow(int s, int t) {
return getFeasibleFlow(s, t, -1);
}
pair<bool, FlowUnit> getMaxFlow(int s, int t) {
return getFeasibleFlow(s, t, 1);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "PushRelabelMaxFlow.h"
using namespace std;
// A sample edge struct for minimum cost maximum flow
// Flow of edge can be found with cap - resCap
// Template Arguments:
// _FlowUnit: the type of the flow
// _CostUnit: the type of the cost
// Constructor Arguments:
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// cap: the initial capacity of this edge
// cost: the cost of this edge
// Fields:
// FlowUnit: the type of the flow
// CostUnit: the type of the cost
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// cap: the initial capacity of this edge
// resCap: the residual capacity of this edge
// cost: the cost of this edge
// Tested:
// https://open.kattis.com/problems/mincostmaxflow
// https://loj.ac/p/102
// https://uoj.ac/problem/487
// https://www.spoj.com/problems/SCITIES/
// https://open.kattis.com/problems/workers
template <class _FlowUnit, class _CostUnit> struct FlowCostEdge {
using FlowUnit = _FlowUnit; using CostUnit = _CostUnit;
int to, rev; FlowUnit cap, resCap; CostUnit cost;
FlowCostEdge(int to, int rev, FlowUnit cap, CostUnit cost)
: to(to), rev(rev), cap(cap), resCap(cap), cost(cost) {}
};
// Computes the maximum flow with the minimum cost in a flow network using the
// Push Relabel algorithm with the highest label selection rule and
// gap relabelling heuristic
// Costs are scaled by a factor that is O(V)
// CostUnit must be integral
// Flow circulations are added to negative cost cycles
// Vertices are 0-indexed
// Template Arguments:
// Edge: a generic edge class (such as FlowCostEdge)
// Required Fields:
// FlowUnit: the type of the flow
// CostUnit: the type of the cost, must be integral
// to: the vertex that this directed edge ends at
// rev: the index in the adjacency list of vertex to of the reverse edge
// resCap: the residual capacity of this edge
// cost: the cost of this edge
// Required Functions:
// constructor(to, rev, cap, cost): initializes the edge to vertex to
// with the reverse index rev, capacity cap, and cost cost
// Constructor Arguments:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// COST_INF: a value for the cost infinity
// COST_EPS: a value for the cost epsilon
// Fields:
// V: the number of vertices in the flow network
// FLOW_EPS: a value for the flow epsilon
// COST_INF: a value for the cost infinity
// COST_EPS: a value for the cost epsilon
// G: an adjacency list of all edges and reverse edges in the flow network
// Functions:
// addEdge(v, w, vwCap, vwCost): adds an edge from v to w with capacity
// vwCap and cost vwCost
// getFlowMinCost(s, t): returns the maximum flow (or circulation if s and t
// are -1) from s to t with the minimum cost
// In practice, has a very small constant
// Time Complexity:
// constructor: O(V)
// addEdge: O(1)
// getFlowMinCost: O(E V^2 log (VC)) where C is the maximum edge cost,
// much faster in practice
// Memory Complexity: O(V + E)
// Tested:
// https://open.kattis.com/problems/mincostmaxflow
// https://loj.ac/p/102
// https://uoj.ac/problem/487
// https://www.spoj.com/problems/SCITIES/
// https://open.kattis.com/problems/workers
template <class Edge>
struct PushRelabelMinCostMaxFlow : public PushRelabelMaxFlow<Edge> {
using MF = PushRelabelMaxFlow<Edge>;
using FlowUnit = typename Edge::FlowUnit;
using CostUnit = typename Edge::CostUnit;
static_assert(is_integral<CostUnit>::value, "CostUnit must be integral");
using MF::V; using MF::G;
using MF::FLOW_EPS; CostUnit COST_INF, COST_EPS, negCost;
PushRelabelMinCostMaxFlow(
int V, FlowUnit FLOW_EPS = FlowUnit(1e-9),
CostUnit COST_INF = numeric_limits<CostUnit>::max(),
CostUnit COST_EPS = CostUnit(1e-9))
: MF(V, FLOW_EPS), COST_INF(COST_INF), COST_EPS(COST_EPS),
negCost(CostUnit()) {}
void addEdge(int v, int w, FlowUnit vwCap, CostUnit vwCost) {
if (v == w) {
if (vwCost < CostUnit()) negCost += vwCap * vwCost;
return;
}
G[v].emplace_back(w, int(G[w].size()), vwCap, vwCost);
G[w].emplace_back(v, int(G[v].size()) - 1, FlowUnit(), -vwCost);
}
pair<FlowUnit, CostUnit> getFlowMinCost(int s = -1, int t = -1) {
CostUnit minCost = CostUnit(), mul = CostUnit(2) << __lg(V);
CostUnit bnd = CostUnit(); vector<int> stk(V), infs(V, 0); int top = 0;
vector<CostUnit> phi(V, CostUnit()); vector<FlowUnit> ex(V, FlowUnit());
auto costP = [&] (int v, const Edge &e) {
int netInfs = infs[v] - infs[e.to]; if (netInfs > 0) return COST_INF;
else if (netInfs < 0) return -COST_INF;
else return e.cost + phi[v] - phi[e.to];
};
auto push = [&] (int v, Edge &e, FlowUnit df, bool pushToStack) {
if (e.resCap < df) df = e.resCap;
int w = e.to; e.resCap -= df; G[w][e.rev].resCap += df;
ex[v] -= df; ex[w] += df;
if (pushToStack && FLOW_EPS < ex[e.to] && ex[e.to] <= df + FLOW_EPS)
stk[top++] = e.to;
};
auto relabel = [&] (int v, CostUnit delta) {
if (delta < COST_INF) phi[v] -= delta + bnd;
else { infs[v]--; phi[v] -= bnd; }
};
auto lookAhead = [&] (int v) {
if (abs(ex[v]) > FLOW_EPS) return false;
CostUnit delta = COST_INF; for (auto &&e : G[v]) {
if (e.resCap <= FLOW_EPS) continue;
CostUnit c = costP(v, e); if (c < -COST_EPS) return false;
else delta = min(delta, c);
}
relabel(v, delta); return true;
};
auto discharge = [&] (int v) {
CostUnit delta = COST_INF; for (int i = 0; i < int(G[v].size()); i++) {
Edge &e = G[v][i]; if (e.resCap <= FLOW_EPS) continue;
if (costP(v, e) < -COST_EPS) {
if (lookAhead(e.to)) { i--; continue; }
push(v, e, ex[v], true); if (abs(ex[v]) <= FLOW_EPS) return;
} else delta = min(delta, costP(v, e));
}
relabel(v, delta); stk[top++] = v;
};
for (int v = 0; v < V; v++) for (auto &&e : G[v]) {
minCost += e.cost * e.resCap; e.cost *= mul; bnd = max(bnd, e.cost);
}
FlowUnit maxFlow = (s == -1 || t == -1) ? FlowUnit() : MF::getFlow(s, t);
while (bnd > 1) {
bnd = max(bnd / CostUnit(8), CostUnit(1)); top = 0;
for (int v = 0; v < V; v++) for (auto &&e : G[v])
if (costP(v, e) < -COST_EPS && e.resCap > FLOW_EPS)
push(v, e, e.resCap, false);
for (int v = 0; v < V; v++) if (ex[v] > FLOW_EPS) stk[top++] = v;
while (top > 0) discharge(stk[--top]);
}
for (int v = 0; v < V; v++)
for (auto &&e : G[v]) { e.cost /= mul; minCost -= e.cost * e.resCap; }
return make_pair(maxFlow, (minCost /= 2) += negCost);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Assigns colors to the edges of an undirected simple graph such that
// no edges that share an endpoint have the same color
// If D is the maximum degree of any vertex, then at most D + 1 colors
// will be used
// Vertices and colors are 0-indexed
// Constructor Arguments:
// V: the number of vertices in the simple graph
// edges: a vector of pairs in the form (v, w) representing
// an undirected edge in the simple graph (no self loops or parallel edges)
// between vertices v and w
// Fields:
// color: a vector of integers in the range [0, D] that has a length equal
// to the length of edges representing the coloring of the edges
// In practice, has a very small constant
// Time Complexity: O(VE)
// Memory Complexity: O(VD) where D is the maximum degree of any vertex
// Tested:
// https://open.kattis.com/problems/gamescheduling
struct EdgeColoring {
vector<int> color;
EdgeColoring(int V, const vector<pair<int, int>> &edges)
: color(edges.size(), 0) {
vector<int> deg(V, 0), fan(V, 0), avail(V, 0);
for (auto &&e : edges) { deg[e.first]++; deg[e.second]++; }
int D = *max_element(deg.begin(), deg.end());
vector<vector<int>> adj(V, vector<int>(D + 1, -1));
vector<int> loc(D + 1, 0); for (auto &&e : edges) {
int v, w; tie(v, w) = e; fan[0] = w; fill(loc.begin(), loc.end(), 0);
int at = v, en = v, d = avail[w], c = avail[v], ind = 0, i = 0;
for (; !loc[d] && (w = adj[v][d]) != -1; d = avail[w]) {
deg[loc[d] = ++ind] = d; fan[ind] = w;
}
for (int cd = d; at != -1; cd ^= c ^ d, at = adj[at][cd])
swap(adj[at][cd], adj[en = at][cd ^ c ^ d]);
deg[loc[d]] = c; while (adj[fan[i]][d] != -1) {
int l = fan[i], r = fan[++i], e = deg[i];
adj[v][e] = l; adj[l][e] = v; adj[r][e] = -1; avail[r] = e;
}
adj[v][d] = fan[i]; adj[fan[i]][d] = v; for (int y : {fan[0], v, en})
for (int &z = avail[y] = 0; adj[y][z] != -1; z++);
}
for (int i = 0; i < int(edges.size()); i++)
while (adj[edges[i].first][color[i]] != edges[i].second) color[i]++;
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Computes the minimum number of colors required to color a simple graph such
// that no two adjacent vertices share the same color
// Vertices are 0-indexed
// Function Arguments:
// V: the number of vertices in the simple graph
// edges: a vector of pairs in the form (v, w) representing
// an undirected edge in the simple graph (no self loops or parallel edges)
// between vertices v and w
// Return Value: the chromatic number (minimum number of colors)
// In practice, has a small constant
// Time Complexity: O(V 2^V)
// Memory Complexity: O(2^V)
// Tested:
// https://judge.yosupo.jp/problem/chromatic_number
int chromaticNumber(int V, const vector<pair<int, int>> &edges) {
int ans = V, PV = 1 << V; vector<int> mask(V, 0), ind(PV), aux(PV);
for (auto &&e : edges) {
mask[e.first] |= 1 << e.second; mask[e.second] |= 1 << e.first;
}
for (int d : {7, 9, 21, 33, 87, 93, 97}) {
long long mod = 1e9 + d; fill(ind.begin(), ind.end(), 0); ind[0] = 1;
fill(aux.begin(), aux.end(), 1); for (int i = 0; i < PV; i++) {
int v = __builtin_ctz(i);
ind[i] = ind[i ^ (1 << v)] + ind[(i ^ (1 << v)) & ~mask[v]];
}
for (int k = 1; k < ans; k++) {
long long chi = 0; for (int i = 0; i < PV; i++) {
int j = i ^ (i >> 1); aux[j] = (long long) aux[j] * ind[j] % mod;
chi += (i & 1) ? aux[j] : -aux[j];
}
if (chi % mod != 0) ans = k;
}
}
return ans;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "../../datastructures/unionfind/UnionFind.h"
#include "../matching/HopcroftKarpMaxMatch.h"
using namespace std;
// Assigns colors to the edges of a bipartite graph such that
// no edges that share an endpoint have the same color
// If D is the maximum degree of any vertex, then exactly D colors
// will be used
// Vertices and colors are 0-indexed
// Constructor Arguments:
// V: the number of vertices in the simple graph
// edges: a vector of pairs in the form (v, w) representing
// an undirected edge in the graph; side[v] != side[w] must hold
// side: the side of the bipartition each vertex is part of
// Fields:
// color: a vector of integers in the range [0, D) that has a length equal
// to the length of edges representing the coloring of the edges
// In practice, has a small constant
// Time Complexity: O(V log V + E log D sqrt (E / D)) where D is the maximum
// degree of any vertex
// Memory Complexity: O(V + E)
// Tested:
// https://judge.yosupo.jp/problem/bipartite_edge_coloring
struct BipartiteEdgeColoring {
struct Pair {
int s, v; Pair(int s, int v) : s(s), v(v) {}
bool operator < (const Pair &o) const { return s > o.s; }
};
int makeDRegular(int &V, vector<pair<int, int>> &edges, vector<bool> &side) {
vector<int> deg(V, 0); for (auto &&e : edges) {
if (side[e.first]) swap(e.first, e.second);
deg[e.first]++; deg[e.second]++;
}
int D = *max_element(deg.begin(), deg.end()); UnionFind uf(V);
for (int s = 0; s < 2; s++) {
std::priority_queue<Pair> PQ;
for (int v = 0; v < V; v++) if (side[v] == s) PQ.emplace(deg[v], v);
while (int(PQ.size()) >= 2) {
Pair a = PQ.top(); PQ.pop(); Pair b = PQ.top(); PQ.pop();
if (a.s + b.s <= D) { uf.join(a.v, b.v); PQ.emplace(a.s + b.s, a.v); }
}
}
vector<int> cnt(2, 0), id(V, -1); int curId = 0;
for (int s = 0; s < 2; s++) for (int v = 0; v < V; v++)
if (uf.find(v) == v && side[v] == s) { id[v] = curId++; cnt[s]++; }
deg.assign(V = max(cnt[0], cnt[1]) * 2, 0); edges.reserve(V * D / 2);
side.reserve(V); side.assign(cnt[0] + cnt[1], true);
fill(side.begin(), side.begin() + cnt[0], false);
for (int s = 0; s < 2; s++) for (; cnt[s] * 2 < V; cnt[s]++)
side.push_back(s);
for (auto &&e : edges) {
deg[e.first = id[uf.find(e.first)]]++;
deg[e.second = id[uf.find(e.second)]]++;
}
for (int v = 0, w = 0; v < V; v++) while (!side[v] && deg[v] < D) {
while (!side[w] || deg[w] == D) w++;
edges.emplace_back(v, w); deg[v]++; deg[w]++;
}
return D;
}
vector<int> eulerianCircuit(
int V, const vector<pair<int, int>> &edges, const vector<int> &inds) {
vector<vector<pair<int, int>>> G(V); vector<int> circuit;
for (int i = 0; i < int(inds.size()); i++) {
int v, w; tie(v, w) = edges[inds[i]];
G[v].emplace_back(w, i); G[w].emplace_back(v, i);
}
vector<bool> vis1(V, false), vis2(inds.size(), false);
vector<pair<int, int>> stk; for (int s = 0; s < V; s++) if (!vis1[s]) {
stk.clear(); stk.emplace_back(s, -1); while (!stk.empty()) {
int v, w, e; tie(v, e) = stk.back(); vis1[v] = true;
if (G[v].empty()) { circuit.emplace_back(e); stk.pop_back(); }
else {
tie(w, e) = G[v].back(); G[v].pop_back();
if (!vis2[e]) { vis2[e] = true; stk.emplace_back(w, e); }
}
}
circuit.pop_back();
}
for (auto &&e : circuit) e = inds[e];
return circuit;
}
vector<int> color;
BipartiteEdgeColoring(int V, vector<pair<int, int>> edges, vector<bool> side)
: color(edges.size(), 0) {
for (auto &&e : edges) assert(side[e.first] != side[e.second]);
int D = makeDRegular(V, edges, side), curCol = 0;
function<void(int, const vector<int> &)> rec = [&] (
int d, const vector<int> &inds) {
if (d == 0) return;
else if (d == 1) {
for (int e : inds) if (e < int(color.size())) color[e] = curCol;
curCol++;
} else if (d % 2 == 0) {
vector<int> circuit = eulerianCircuit(V, edges, inds), half1, half2;
half1.reserve(circuit.size() / 2); half2.reserve(circuit.size() / 2);
for (int i = 0; i < int(circuit.size()); i += 2) {
half1.push_back(circuit[i]); half2.push_back(circuit[i + 1]);
}
rec(d / 2, half1); rec(d / 2, half2);
} else {
vector<vector<int>> G(V); for (int e : inds) {
int v, w; tie(v, w) = edges[e]; G[v].push_back(w); G[w].push_back(v);
}
vector<int> unmatched; HopcroftKarpMaxMatch mm(G, side);
for (int e : inds) {
int v, w; tie(v, w) = edges[e]; if (mm.mate[v] == w) {
mm.mate[v] = -1; if (e < int(color.size())) color[e] = curCol;
} else unmatched.push_back(e);
}
curCol++; rec(d - 1, unmatched);
}
};
vector<int> inds(edges.size()); iota(inds.begin(), inds.end(), 0);
rec(D, inds);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
#include "../../datastructures/trees/binarysearchtrees/Splay.h"
using namespace std;
// Link Cut Tree supporting path operations on a dynamic tree,
// backed by a splay tree
// Vertices are 0-indexed
// Template Arguments:
// Node: a generic node class (sample structs are in BSTNode)
// Required Fields:
// Data: the data type
// Lazy: the lazy type
// static const RANGE_UPDATES: a boolean indicating whether
// range updates are permitted
// static const RANGE_QUERIES: a boolean indicating whether
// range queries are permitted
// static const RANGE_REVERSALS: a boolean indicating whether
// range reversals are permitted
// sz: the number of nodes in the subtree
// l: a pointer to the left child
// r: a pointer to the right child
// p: a pointer to the parent
// val: only required if getFirst is called, the value being stored
// sbtr: only required if RANGE_QUERIES is true to support path queries,
// the aggregate value of type Data for the subtree
// Required Functions:
// constructor(v): initializes a node with the value v
// update(): updates the current node's information based on its children
// propagate(): propagates the current node's lazy information (including
// rev) to its children
// apply(v): applies the lazy value v to the node
// reverse(): only required if RANGE_REVERSALS is true to support
// rerooting, reverse this node's subtree (aggregate data
// and any lazy flags should be reversed)
// static qdef(): returns the query default value
// Constructor Arguments:
// A: a vector of type Node::Data
// Functions:
// makeRoot(x): only valid if Node::RANGE_REVERSALS is true, makes x the
// root of its connected component
// lca(x, y): returns the lowest common ancestor of x and y in
// the current forest, returns -1 if not connected
// connected(x, y): returns whether x and y are connected
// link(x, y): only valid if Node::RANGE_REVERSALS is true, links the nodes
// x and y, assumes x and y are not connected, reroots the tree at node y
// safeLink(x, y): only valid if Node::RANGE_REVERSALS is true, links
// the nodes x and y, returns false if already connected, true otherwise,
// reroots the tree at node y
// linkParent(par, ch): makes par the parent of the node ch, returns false if
// par and ch are already connected, true otherwise
// cut(x, y): only valid if Node::RANGE_REVERSALS is true, cuts the edge
// between nodes x and y, returns false if this edge doesn't exist,
// true otherwise, reroots the forest at node x
// cutParent(x): cuts the edge between node x and its parent, returns false
// if no parent exists (x is a root), true otherwise
// findParent(x): returns the parent of node x, -1 if it doesn't exist
// findRoot(x): returns the root of the forest containing node x
// depth(x): returns the depth of node x, where the depth of the root is 0
// kthParent(x): returns the kth parent of node x (0th parent is x,
// 1st parent is the parent of x), -1 if it doesn't exist
// updateVertex(x, v): updates the node x with the lazy value v
// updatePathFromRoot(to, v): only valid if Node::RANGE_UPDATES is true,
// updates the path from the root of the forest containing
// node to, to node to, with the lazy value v
// updatePath(from, to, v): only valid if Node::RANGE_UPDATES and
// Node::RANGE_REVERSALS are true, updates the path from node
// from to node to, reroots the forest at node from, with the lazy value v,
// reroots the forest at node from
// queryVertex(x): returns the value of node x
// queryPathFromRoot(to): only valid if Node::RANGE_QUERIES is true,
// returns the aggregate value of the path from the root of the forest
// containing node to, to node to
// queryPath(from, to): only valid if Node::RANGE_QUERIES and
// Node::RANGE_REVERSALS are true, returns the aggregate value of the path
// from node from to node to, reroots the forest at node from, reroots the
// forest at node from
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(N)
// makeRoot, lca, connected, link, safeLink, linkParent, cut, cutParent,
// findParent, findRoot, depth, kthParent, updateVertex,
// updatePathFromRoot, updatePath, queryVertex, queryPathFromRoot,
// queryPath: O(log N) amortized
// Memory Complexity: O(N)
// Tested:
// https://dmoj.ca/problem/coi08p2
// https://codeforces.com/contest/13/problem/E
// https://dmoj.ca/problem/ds5easy
// https://www.spoj.com/problems/QTREE2/
// https://judge.yosupo.jp/problem/dynamic_tree_vertex_set_path_composite
// https://oj.uz/problem/view/JOI13_synchronization
template <class Node> struct LCT : public Splay<Node, vector<Node>> {
using Tree = Splay<Node, vector<Node>>;
using Tree::TR; using Tree::makeNode; using Tree::splay; using Tree::select;
using Data = typename Node::Data; using Lazy = typename Node::Lazy;
int vert(Node *x) { return x - TR.data(); }
Node *access(Node *x) {
Node *last = nullptr;
for (Node *y = x; y; y = y->p) { splay(y); y->r = last; last = y; }
splay(x); return last;
}
template <const int _ = Node::RANGE_REVERSALS>
typename enable_if<_>::type makeRoot(Node *x) { access(x); x->reverse(); }
Node *findMin(Node *x) {
for (x->propagate(); x->l; (x = x->l)->propagate());
splay(x); return x;
}
Node *findMax(Node *x) {
for (x->propagate(); x->r; (x = x->r)->propagate());
splay(x); return x;
}
template <const int _ = Node::RANGE_REVERSALS>
typename enable_if<_>::type makeRoot(int x) { makeRoot(&TR[x]); }
int lca(int x, int y) {
if (x == y) return x;
access(&TR[x]); Node *ny = access(&TR[y]); return TR[x].p ? vert(ny) : -1;
}
bool connected(int x, int y) { return lca(x, y) != -1; }
template <const int _ = Node::RANGE_REVERSALS>
typename enable_if<_>::type link(int x, int y) {
makeRoot(y); TR[y].p = &TR[x];
}
template <const int _ = Node::RANGE_REVERSALS>
typename enable_if<_, bool>::type safeLink(int x, int y) {
if (connected(x, y)) return false;
link(x, y); return true;
}
bool linkParent(int par, int ch) {
access(&TR[ch]); if (TR[ch].l) return false;
TR[ch].p = &TR[par]; return true;
}
template <const int _ = Node::RANGE_REVERSALS>
typename enable_if<_, bool>::type cut(int x, int y) {
makeRoot(x); access(&TR[y]);
if (&TR[x] != TR[y].l || TR[x].r) return false;
TR[y].l->p = nullptr; TR[y].l = nullptr; return true;
}
bool cutParent(int x) {
access(&TR[x]); if (!TR[x].l) return false;
TR[x].l->p = nullptr; TR[x].l = nullptr; return true;
}
int findParent(int x) {
access(&TR[x]); return TR[x].l ? vert(findMax(TR[x].l)) : -1;
}
int findRoot(int x) { access(&TR[x]); return vert(findMin(&TR[x])); }
int depth(int x) { access(&TR[x]); return TR[x].l ? TR[x].l->sz : 0; }
int kthParent(int x, int k) {
int d = depth(x); Node *nx = &TR[x];
return k <= d ? vert(select(nx, d - k)) : -1;
}
void updateVertex(int x, const Lazy &v) {
access(&TR[x]); Node *l = TR[x].l; TR[x].l = nullptr;
TR[x].apply(v); TR[x].propagate(); TR[x].update(); TR[x].l = l;
}
template <const int _ = Node::RANGE_UPDATES>
typename enable_if<_>::type updatePathFromRoot(int to, const Lazy &v) {
access(&TR[to]); TR[to].apply(v);
}
template <const int _ = Node::RANGE_UPDATES && Node::RANGE_REVERSALS>
typename enable_if<_, bool>::type updatePath(
int from, int to, const Lazy &v) {
makeRoot(from); access(&TR[to]);
if (from != to && !TR[from].p) return false;
TR[to].apply(v); return true;
}
Data queryVertex(int x) { access(&TR[x]); return TR[x].val; }
template <const int _ = Node::RANGE_QUERIES>
typename enable_if<_, Data>::type queryPathFromRoot(int to) {
access(&TR[to]); return TR[to].sbtr;
}
template <const int _ = Node::RANGE_QUERIES && Node::RANGE_REVERSALS>
typename enable_if<_, Data>::type queryPath(int from, int to) {
makeRoot(from); access(&TR[to]);
return from == to || TR[from].p ? TR[to].sbtr : Node::qdef();
}
LCT(const vector<Data> &A) {
TR.reserve(A.size()); for (auto &&a : A) makeNode(a);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Top Tree supporting path and subtree operations on a dynamic tree
// Vertices are 0-indexed
// Template Arguments:
// C: struct to combine data and lazy values
// Required Fields:
// Data: the data type
// Lazy: the lazy type
// Required Functions:
// static qdef(): returns the query default value of type Data
// static merge(l, r): returns the values l of type Data merged with
// r of type Data, must be associative
// static applyLazy(l, r, k): returns the value r of type Lazy applied to
// l of type Data over a segment of length k, must be associative
// static mergeLazy(l, r): returns the values l of type Lazy merged with
// r of type Lazy, must be associative
// static revData(v): reverses the value v of type Data
// Sample Struct: supporting range assignments and range sum queries
// struct C {
// using Data = int;
// using Lazy = int;
// static Data qdef() { return 0; }
// static Lazy ldef() { return numeric_limits<int>::min(); }
// static Data merge(const Data &l, const Data &r) { return l + r; }
// static Data applyLazy(const Data &l, const Lazy &r, int k) {
// return r * k;
// }
// static Lazy mergeLazy(const Lazy &l, const Lazy &r) { return r; }
// static void revData(Data &v) {}
// };
// Constructor Arguments:
// A: a vector of type C::Data
// Functions:
// makeRoot(x): makes x the root of its connected component
// lca(x, y): returns the lowest common ancestor of x and y in
// the current forest, returns -1 if not connected
// connected(x, y): returns whether x and y are connected
// link(par, ch): makes par the parent of the node ch, assumes par and ch
// are not connected, reroots the tree at node par
// safeLink(par, ch): makes par the parent of the node ch, returns false if
// already connected, true otherwise, reroots the tree at node par
// cutParent(x): cuts the edge between node x and its parent, returns false
// if no parent exists (x is a root), true otherwise
// findParent(x): returns the parent of node x, -1 if it doesn't exist
// findRoot(x): returns the root of the forest containing node x
// depth(x): returns the depth of node x, where the depth of the root is 0
// kthParent(x): returns the kth parent of node x (0th parent is x,
// 1st parent is the parent of x), -1 if it doesn't exist
// updateVertex(x, v): updates the node x with the lazy value v
// updatePathFromRoot(to, v): updates the path from the root of the forest
// containing node to, to node to, with the lazy value v
// updatePath(from, to, v): updates the path from node
// from to node to, reroots the forest at node from, with the lazy value v,
// reroots the forest at node from
// updateSubtree(x): updates the subtree of node x with the lazy value v
// queryVertex(x): returns the value of node x
// queryPathFromRoot(to): returns the aggregate value of the path from
// the root of the forest containing node to, to node to
// queryPath(from, to): returns the aggregate value of the path
// from node from to node to, reroots the forest at node from, reroots the
// forest at node from
// querySubtree(x): returns the aggregate value of the subtree of node x
// In practice, has a large constant
// Time Complexity:
// constructor: O(N)
// makeRoot, lca, connected, link, safeLink, cutParent,
// findParent, findRoot, depth, kthParent, updateVertex,
// updatePathFromRoot, updatePath, updateSubtree, queryVertex,
// queryPathFromRoot, queryPath, querySubtree: O(log N) amortized
// Memory Complexity: O(N)
// Tested:
// https://www.spoj.com/problems/QTREE2/
// https://judge.yosupo.jp/problem/dynamic_tree_vertex_set_path_composite
// https://judge.yosupo.jp/problem/dynamic_tree_subtree_add_subtree_sum
// https://dmoj.ca/problem/ds5
template <class C> struct TopTree {
using Data = typename C::Data; using Lazy = typename C::Lazy;
struct Node {
bool rev, aux; int szpath, szvtr; array<Node *, 4> ch; Node *p;
Lazy lzpath, lzvtr; Data val, path, vtr;
Node(bool aux, const Data &v)
: rev(false), aux(aux), szpath(aux ? 0 : 1), szvtr(0),
p(nullptr), lzpath(C::ldef()), lzvtr(C::ldef()), val(v),
path(aux ? C::qdef() : v), vtr(C::qdef()) {
ch.fill(nullptr);
}
void applyVal(const Lazy &v) { val = C::applyLazy(val, v, 1); }
void applyPath(const Lazy &v) {
applyVal(v); lzpath = C::mergeLazy(lzpath, v);
if (szpath > 0) path = C::applyLazy(path, v, szpath);
}
void applyVtr(const Lazy &v, bool ap = true) {
lzvtr = C::mergeLazy(lzvtr, v);
if (szvtr > 0) vtr = C::applyLazy(vtr, v, szvtr);
if (!aux && ap) applyPath(v);
}
void update() {
szpath = aux ? 0 : 1; path = aux ? C::qdef() : val;
szvtr = 0; vtr = C::qdef(); for (int i = 0; i < 4; i++) if (ch[i]) {
vtr = C::merge(vtr, ch[i]->vtr); szvtr += ch[i]->szvtr; if (i < 2) {
path = i ? C::merge(path, ch[i]->path) : C::merge(ch[i]->path, path);
szpath += ch[i]->szpath;
} else { vtr = C::merge(vtr, ch[i]->path); szvtr += ch[i]->szpath; }
}
}
void propagate() {
if (rev) {
for (int i = 0; i < 2; i++) if (ch[i]) ch[i]->reverse();
rev = false;
}
if (lzpath != C::ldef() && !aux) {
for (int i = 0; i < 2; i++) if (ch[i]) ch[i]->applyPath(lzpath);
lzpath = C::ldef();
}
if (lzvtr != C::ldef()) {
for (int i = 0; i < 4; i++) if (ch[i]) ch[i]->applyVtr(lzvtr, i >= 2);
lzvtr = C::ldef();
}
}
void reverse() { rev = !rev; swap(ch[0], ch[1]); C::revData(path); }
};
vector<Node> TR; vector<Node *> deleted, stk;
Node *makeNode(bool aux, const Data &v) {
if (deleted.empty()) { TR.emplace_back(aux, v); return &TR.back(); }
Node *x = deleted.back(); deleted.pop_back(); *x = Node(aux, v); return x;
}
int vert(Node *x) { return x - TR.data(); }
bool isRoot(Node *x, bool t) {
if (t) return !x->p || !x->aux || !x->p->aux;
else return !x->p || (x != x->p->ch[0] && x != x->p->ch[1]);
}
void connect(Node *x, Node *p, int i) {
if (x) x->p = p;
if (i != -1) p->ch[i] = x;
}
int findInd(Node *x) {
for (int i = 0; i < 4; i++) if (x->p->ch[i] == x) return i;
return -1;
}
void rotate(Node *x, int t) {
Node *p = x->p, *g = p->p; bool isL = x == p->ch[t];
if (g) connect(x, g, findInd(p));
else x->p = nullptr;
connect(x->ch[t ^ isL], p, t ^ !isL); connect(p, x, t ^ isL);
p->update();
}
void splay(Node *x, int t) {
while (!isRoot(x, t)) {
Node *p = x->p, *g = p->p;
if (!isRoot(p, t)) rotate((x == p->ch[t]) == (p == g->ch[t]) ? p : x, t);
rotate(x, t);
}
x->update();
}
Node *select(Node *&root, int k) {
Node *last = nullptr; while (root) {
(last = root)->propagate();
int t = root->ch[0] ? root->ch[0]->szpath : 0;
if (t > k) root = root->ch[0];
else if (t < k) { root = root->ch[1]; k -= t + 1; }
else break;
}
if (last) splay(root = last, 0);
return root;
}
void add(Node *x, Node *y) {
Node *z = makeNode(true, C::qdef());
connect(y->ch[2], z, 2); connect(x, z, 3); connect(z, y, 2); z->update();
}
void rem(Node *x) {
Node *p = x->p, *g = p->p; connect(p->ch[findInd(x) ^ 1], g, findInd(p));
splay(g, 2); deleted.push_back(x->p); x->p = nullptr;
}
void touch(Node *x) {
for (Node *y = x; y->p; y = y->p) stk.push_back(y->p);
for (; !stk.empty(); stk.pop_back()) stk.back()->propagate();
x->propagate();
}
Node *nextChain(Node *x) {
splay(x, 0); if (!x->p) return nullptr;
Node *p = x->p; splay(p, 2); return p->p;
}
Node *access(Node *x) {
touch(x); Node *last = nullptr; for (Node *y = x; y; y = nextChain(y)) {
splay(y, 0); if (last) rem(last);
if (y->ch[1]) add(y->ch[1], y);
connect(last, y, 1); last = y;
}
splay(x, 0); return last;
}
void makeRoot(Node *x) { access(x); x->reverse(); }
Node *findMin(Node *x) {
for (x->propagate(); x->ch[0]; (x = x->ch[0])->propagate());
splay(x, 0); return x;
}
Node *findMax(Node *x) {
for (x->propagate(); x->ch[1]; (x = x->ch[1])->propagate());
splay(x, 0); return x;
}
void makeRoot(int x) { makeRoot(&TR[x]); }
int lca(int x, int y) {
if (x == y) return x;
access(&TR[x]); Node *ny = access(&TR[y]); return TR[x].p ? vert(ny) : -1;
}
bool connected(int x, int y) { return lca(x, y) != -1; }
void link(int par, int ch) {
makeRoot(par); access(&TR[ch]); add(&TR[par], &TR[ch]);
}
bool safeLink(int par, int ch) {
if (connected(par, ch)) return false;
link(par, ch); return true;
}
bool cutParent(int x) {
access(&TR[x]); if (!TR[x].ch[0]) return false;
TR[x].ch[0]->p = nullptr; TR[x].ch[0] = nullptr; return true;
}
int findParent(int x) {
access(&TR[x]); return TR[x].ch[0] ? vert(findMax(TR[x].ch[0])) : -1;
}
int findRoot(int x) { access(&TR[x]); return vert(findMin(&TR[x])); }
int depth(int x) {
access(&TR[x]); return TR[x].ch[0] ? TR[x].ch[0]->szpath : 0;
}
int kthParent(int x, int k) {
int d = depth(x); Node *nx = &TR[x];
return k <= d ? vert(select(nx, d - k)) : -1;
}
void updateVertex(int x, const Lazy &v) {
access(&TR[x]); TR[x].applyVal(v); TR[x].update();
}
void updatePathFromRoot(int to, const Lazy &v) {
access(&TR[to]); TR[to].applyPath(v);
}
bool updatePath(int from, int to, const Lazy &v) {
makeRoot(from); access(&TR[to]);
if (from != to && !TR[from].p) return false;
TR[to].applyPath(v); return true;
}
void updateSubtree(int x, const Lazy &v) {
access(&TR[x]); TR[x].applyVal(v);
for (int i = 2; i < 4; i++) if (TR[x].ch[i]) TR[x].ch[i]->applyVtr(v);
}
Data queryVertex(int x) { access(&TR[x]); return TR[x].val; }
Data queryPathFromRoot(int to) { access(&TR[to]); return TR[to].sbtr; }
Data queryPath(int from, int to) {
makeRoot(from); access(&TR[to]);
return from == to || TR[from].p ? TR[to].path : C::qdef();
}
Data querySubtree(int x) {
access(&TR[x]); Data ret = TR[x].val;
for (int i = 2; i < 4; i++) if (TR[x].ch[i]) {
ret = C::merge(C::merge(ret, TR[x].ch[i]->vtr), TR[x].ch[i]->path);
}
return ret;
}
TopTree(const vector<Data> &A) {
TR.reserve(A.size() * 2); for (auto &&a : A) makeNode(false, a);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Adjacency List representation of a graph using linked list,
// implemented with fixed size arrays if reserveEdges is called beforehand
// Vertices are 0-indexed
// Constructor Arguments:
// V: the number of vertices in the graph
// Functions:
// reserveDiEdges(maxEdges): reserves space for maxEdges directed edges
// (bidirectional edges take up twice as much space)
// addDiEdge(from, to): adds a directed edge from the vertex from,
// to the vertex to
// addBiEdge(v, w): adds a bidirectional edge between vertices v and w
// operator [v]: returns a struct with the begin() and end() defined to
// iterate over the vertices adjacent to vertex v
// size(): returns the number of vertices in the graph
// In practice, addBiEdge, addDiEdge have a small constant, operator []
// has a moderate constant
// Graph construction is faster than static graphs and adjacency lists
// Graph traveral is slower than static graphs and adjacency lists
// Uses less memory than static graphs and adjacency lists
// Time Complexity:
// constructor: O(V)
// addDiEdge: O(1) amortized
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://judge.yosupo.jp/problem/lca
struct LinkedListGraph {
vector<int> HEAD, TO, NXT; LinkedListGraph(int V) : HEAD(V, -1) {}
void reserveDiEdges(int maxEdges) {
TO.reserve(maxEdges); NXT.reserve(maxEdges);
}
void addDiEdge(int from, int to) {
NXT.push_back(HEAD[from]); HEAD[from] = int(TO.size()); TO.push_back(to);
}
void addBiEdge(int v, int w) { addDiEdge(v, w); addDiEdge(w, v); }
struct Iterator {
const LinkedListGraph &G; int i;
Iterator(const LinkedListGraph &G, int i) : G(G), i(i) {}
Iterator &operator ++ () { i = G.NXT[i]; return *this; }
int operator * () const { return G.TO[i]; }
bool operator != (const Iterator &it) const { return i != it.i; }
};
struct Adj {
const LinkedListGraph &G; int v;
Adj(const LinkedListGraph &G, int v) : G(G), v(v) {}
const Iterator begin() const { return Iterator(G, G.HEAD[v]); }
const Iterator end() const { return Iterator(G, -1); }
};
const Adj operator [] (int v) const { return Adj(*this, v); }
int size() const { return HEAD.size(); }
};
// Adjacency List representation of a weighted graph using linked list,
// implemented with fixed size arrays if reserveEdges is called beforehand
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the weighted graph
// Constructor Arguments:
// V: the number of vertices in the weighted graph
// Functions:
// reserveDiEdges(maxEdges): reserves space for maxEdges directed edges
// (bidirectional edges take up twice as much space)
// addDiEdge(from, to, weight): adds a directed edge from the vertex from,
// to the vertex to, with a weight of weight
// addBiEdge(v, w, weight): adds a bidirectional edge between vertices v
// and w, with a weight of weight
// operator [v]: returns a struct with the begin() and end() defined to
// iterate over the edges incident to vertex v
// size(): returns the number of vertices in the graph
// In practice, addBiEdge, addDiEdge have a small constant, operator []
// has a moderate constant
// Graph construction is faster than static graphs and adjacency lists
// Graph traveral is slower than static graphs and adjacency lists
// Uses less memory than static graphs and adjacency lists
// Time Complexity:
// constructor: O(V)
// addBiEdge, addDiEdge: O(1) amortized
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://dmoj.ca/problem/rte16s3
template <class T> struct LinkedListWeightedGraph {
vector<int> HEAD, TO, NXT; vector<T> WEIGHT;
LinkedListWeightedGraph(int V) : HEAD(V, -1) {}
void reserveDiEdges(int maxEdges) {
TO.reserve(maxEdges); NXT.reserve(maxEdges); WEIGHT.reserve(maxEdges);
}
void addDiEdge(int from, int to, T weight) {
NXT.push_back(HEAD[from]); HEAD[from] = int(TO.size());
TO.push_back(to); WEIGHT.push_back(weight);
}
void addBiEdge(int v, int w, T weight) {
addDiEdge(v, w, weight); addDiEdge(w, v, weight);
}
struct Iterator {
const LinkedListWeightedGraph &G; int i;
Iterator(const LinkedListWeightedGraph &G, int i) : G(G), i(i) {}
Iterator &operator ++ () { i = G.NXT[i]; return *this; }
pair<int, T> operator * () const {
return make_pair(G.TO[i], G.WEIGHT[i]);
}
bool operator != (const Iterator &it) const { return i != it.i; }
};
struct Adj {
const LinkedListWeightedGraph &G; int v;
Adj(const LinkedListWeightedGraph &G, int v) : G(G), v(v) {}
const Iterator begin() const { return Iterator(G, G.HEAD[v]); }
const Iterator end() const { return Iterator(G, -1); }
};
const Adj operator [] (int v) const { return Adj(*this, v); }
int size() const { return HEAD.size(); }
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Static Graph implemented with fixed size arrays
// if reserveEdges is called beforehand
// build must be called before the graph can be used, and edges cannot be
// added afterwards
// Vertices are 0-indexed
// Constructor Arguments:
// V: the number of vertices in the graph
// Functions:
// reserveDiEdges(maxEdges): reserves space for maxEdges directed edges
// (bidirectional edges take up twice as much space)
// addDiEdge(from, to): adds a directed edge from the vertex from,
// to the vertex to
// addBiEdge(v, w): adds a bidirectional edge between vertices v and w
// operator [v]: returns a struct with the begin() and end() defined to
// iterate over the vertices adjacent to vertex v
// size(): returns the number of vertices in the graph
// build(): builds a graph using the edges that have been added
// In practice, addBiEdge and addDiEdge have a small constant, build has a
// moderate constant, and operator [] has a very small constant
// Graph construction is faster than adjacency lists, but slower than
// linked lists
// Graph traveral is faster than adjacency lists and linked lists
// Uses less memory than adjacency lists, but more memory than linked lists
// Time Complexity:
// constructor: O(V)
// addDiEdge: O(1) amortized
// build: O(V + E)
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://judge.yosupo.jp/problem/lca
struct StaticGraph {
vector<int> ST, TO, A, B; StaticGraph(int V) : ST(V + 1, 0) {}
void reserveDiEdges(int maxEdges) {
TO.reserve(maxEdges); A.reserve(maxEdges); B.reserve(maxEdges);
}
void addDiEdge(int from, int to) {
ST[from]++; A.push_back(from); B.push_back(to);
}
void addBiEdge(int v, int w) { addDiEdge(v, w); addDiEdge(w, v); }
void build() {
partial_sum(ST.begin(), ST.end(), ST.begin()); TO = B;
for (int e = 0; e < int(A.size()); e++) TO[--ST[A[e]]] = B[e];
}
struct Iterator {
const StaticGraph &G; int i;
Iterator(const StaticGraph &G, int i) : G(G), i(i) {}
Iterator &operator ++ () { i++; return *this; }
int operator * () const { return G.TO[i]; }
bool operator != (const Iterator &it) const { return i != it.i; }
};
struct Adj {
const StaticGraph &G; int v;
Adj(const StaticGraph &G, int v) : G(G), v(v) {}
const Iterator begin() const { return Iterator(G, G.ST[v]); }
const Iterator end() const { return Iterator(G, G.ST[v + 1]); }
};
const Adj operator [] (int v) const { return Adj(*this, v); }
int size() const { return int(ST.size()) - 1; }
};
// Static Weighted Graph implemented with fixed size arrays
// if reserveEdges is called beforehand
// build must be called before the graph can be used, and edges cannot be
// added afterwards
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the weighted graph
// Constructor Arguments:
// V: the number of vertices in the weighted graph
// Functions:
// reserveDiEdges(maxEdges): reserves space for maxEdges directed edges
// (bidirectional edges take up twice as much space)
// addDiEdge(from, to, weight): adds a directed edge from the vertex from,
// to the vertex to, with a weight of weight
// addBiEdge(v, w, weight): adds a bidirectional edge between vertices v
// and w, with a weight of weight
// operator [v]: returns a struct with the begin() and end() defined to
// iterate over the edges incident to vertex v
// size(): returns the number of vertices in the graph
// build(): builds a graph using the edges that have been added
// In practice, addBiEdge and addDiEdge have a small constant, build has a
// moderate constant, and operator [] has a very small constant
// Graph construction is faster than adjacency lists, but slower than
// linked lists
// Graph traveral is faster than adjacency lists and linked lists
// Uses less memory than adjacency lists, but more memory than linked lists
// Time Complexity:
// constructor: O(V)
// addBiEdge, addDiEdge: O(1) amortized
// build: O(V + E)
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://dmoj.ca/problem/rte16s3
template <class T> struct StaticWeightedGraph {
vector<int> ST, TO, A, B; vector<T> C, WEIGHT;
StaticWeightedGraph(int V) : ST(V + 1, 0) {}
void reserveDiEdges(int maxEdges) {
TO.reserve(maxEdges); A.reserve(maxEdges); B.reserve(maxEdges);
}
void addDiEdge(int from, int to, T weight) {
ST[from]++; A.push_back(from); B.push_back(to); C.push_back(weight);
}
void addBiEdge(int v, int w, T weight) {
addDiEdge(v, w, weight); addDiEdge(w, v, weight);
}
void build() {
partial_sum(ST.begin(), ST.end(), ST.begin()); TO = B; WEIGHT = C;
for (int e = 0; e < int(A.size()); e++) {
TO[--ST[A[e]]] = B[e]; WEIGHT[ST[A[e]]] = C[e];
}
}
struct Iterator {
const StaticWeightedGraph &G; int i;
Iterator(const StaticWeightedGraph &G, int i) : G(G), i(i) {}
Iterator &operator ++ () { i++; return *this; }
pair<int, T> operator * () const {
return make_pair(G.TO[i], G.WEIGHT[i]);
}
bool operator != (const Iterator &it) const { return i != it.i; }
};
struct Adj {
const StaticWeightedGraph &G; int v;
Adj(const StaticWeightedGraph &G, int v) : G(G), v(v) {}
const Iterator begin() const { return Iterator(G, G.ST[v]); }
const Iterator end() const { return Iterator(G, G.ST[v + 1]); }
};
const Adj operator [] (int v) const { return Adj(*this, v); }
int size() const { return int(ST.size()) - 1; }
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Adjacency List representation of a graph
// Vertices are 0-indexed
// Constructor Arguments:
// V: the number of vertices in the graph
// Functions:
// addDiEdge(from, to): adds a directed edge from the vertex from,
// to the vertex to
// addBiEdge(v, w): adds a bidirectional edge between vertices v and w
// operator [v]: returns a reference to a list of vertices adjacent to v
// size(): returns the number of vertices in the graph
// In practice, addBiEdge, addDiEdge have a moderate constant, operator []
// has a small constant
// Graph construction is slower than static graphs and linked lists
// Graph traveral is faster than static graphs, but slower than linked lists
// Uses more memory than static graphs and linked lists
// Time Complexity:
// constructor: O(V)
// addBiEdge, addDiEdge: O(1) amortized
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://judge.yosupo.jp/problem/lca
struct AdjacencyListGraph : public vector<vector<int>> {
AdjacencyListGraph(int V) : vector<vector<int>>(V) {}
void addDiEdge(int from, int to) { at(from).push_back(to); }
void addBiEdge(int v, int w) { addDiEdge(v, w); addDiEdge(w, v); }
};
// Adjacency List representation of a weighted graph
// Vertices are 0-indexed
// Template Arguments:
// T: the type of the weight of the edges in the weighted graph
// Constructor Arguments:
// V: the number of vertices in the weighted graph
// Functions:
// addDiEdge(from, to, weight): adds a directed edge from the vertex from,
// to the vertex to, with a weight of weight
// addBiEdge(v, w, weight): adds a bidirectional edge between vertices v
// and w, with a weight of weight
// operator [v]: returns a reference to a list of edges incident to v
// size(): returns the number of vertices in the graph
// In practice, addBiEdge, addDiEdge have a moderate constant, operator []
// has a small constant
// Graph construction is slower than static graphs and linked lists
// Graph traveral is faster than static graphs, but slower than linked lists
// Uses more memory than static graphs and linked lists
// Time Complexity:
// constructor: O(V)
// addBiEdge, addDiEdge: O(1) amortized
// operator [], size: O(1)
// Memory Complexity: O(V + E)
// Tested:
// https://dmoj.ca/problem/rte16s3
template <class T>
struct AdjacencyListWeightedGraph : public vector<vector<pair<int, T>>> {
AdjacencyListWeightedGraph(int V) : vector<vector<pair<int, T>>>(V) {}
void addDiEdge(int from, int to, T weight) {
this->at(from).emplace_back(to, weight);
}
void addBiEdge(int v, int w, T weight) {
addDiEdge(v, w, weight); addDiEdge(w, v, weight);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Runs a callback on the triangles in a simple graph
// Vertices are 0-indexed
// Template Arguments:
// F: the type of the function f
// Function Arguments:
// V: the number of vertices in the simple graph
// edges: a vector of pairs in the form (v, w) representing
// an undirected edge in the simple graph (no self loops or parallel edges)
// between vertices v and w
// f(a, b, c, i, j, k): the function to run a callback on for each triangle
// where a, b, c are the vertices in the triangle, and i, j, k are the
// indices of the edges in the triangle
// In practice, has a very small constant
// Time Complexity: O(V + E sqrt E)
// Memory Complexity: O(V + E)
// Tested:
// Fuzz and Stress Tested
// https://mcpt.ca/problem/lcc19c3s4
// https://open.kattis.com/problems/gottacatchemall
// https://judge.yosupo.jp/problem/enumerate_triangles
// https://dmoj.ca/problem/year2019p7
template <class F>
void triangles(int V, const vector<pair<int, int>> &edges, F f) {
vector<int> st(V + 1, 0), ind(V, 0), to(edges.size()), eInd(edges.size());
vector<int> &d = ind; for (auto &&e : edges) { d[e.first]++; d[e.second]++; }
auto cmp = [&] (int v, int w) { return d[v] == d[w] ? v > w : d[v] > d[w]; };
for (auto &&e : edges) st[cmp(e.first, e.second) ? e.second : e.first]++;
partial_sum(st.begin(), st.end(), st.begin());
for (int i = 0, v, w; i < int(edges.size()); i++) {
tie(v, w) = edges[i]; if (cmp(v, w)) swap(v, w);
to[--st[v]] = w; eInd[st[v]] = i;
}
fill(ind.begin(), ind.end(), -1); for (int v = 0; v < V; v++) {
for (int e1 = st[v]; e1 < st[v + 1]; e1++) ind[to[e1]] = eInd[e1];
for (int e1 = st[v]; e1 < st[v + 1]; e1++)
for (int w = to[e1], e2 = st[w]; e2 < st[w + 1]; e2++)
if (ind[to[e2]] != -1)
f(v, w, to[e2], eInd[e1], eInd[e2], ind[to[e2]]);
for (int e1 = st[v]; e1 < st[v + 1]; e1++) ind[to[e1]] = -1;
}
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Finds a directed cycle in a directed graph (including self loops and
// parallel edges)
// Vertices are 0-indexed
// Constructor Arguments:
// G: a generic directed graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the graph
// Fields:
// cycle: a vector of the vertices in the directed cycle with the first
// vertex equal to the last vertex; if there is no cycle, then it is empty
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// Memory Complexity: O(V)
// Tested:
// Stress Tested
// https://cses.fi/problemset/task/1678
// https://judge.yosupo.jp/problem/cycle_detection
struct DirectedCycle {
int V; vector<bool> vis, onStk; vector<int> to, cycle;
template <class Digraph> void dfs(const Digraph &G, int v) {
vis[v] = onStk[v] = true; for (int w : G[v]) {
if (!vis[w]) { to[w] = v; dfs(G, w); }
else if (onStk[w]) {
for (int x = v; x != w; x = to[x]) cycle.push_back(x);
cycle.push_back(w); cycle.push_back(v);
reverse(cycle.begin(), cycle.end());
}
if (!cycle.empty()) return;
}
onStk[v] = false;
}
template <class Digraph> DirectedCycle(const Digraph &G)
: V(G.size()), vis(V, false), onStk(V, false), to(V) {
for (int v = 0; v < V && cycle.empty(); v++) if (!vis[v]) dfs(G, v);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Finds a cycle in an undirected graph (including self loops and
// parallel edges)
// Vertices are 0-indexed
// Constructor Arguments:
// G: a generic undirected graph structure
// Required Functions:
// operator [v] const: iterates over the adjacency list of vertex v
// (which is a list of ints)
// size() const: returns the number of vertices in the graph
// Fields:
// cycle: a vector of the vertices in the cycle with the first vertex equal
// to the last vertex; if there is no cycle, then it is empty
// In practice, has a moderate constant
// Time Complexity:
// constructor: O(V + E)
// Memory Complexity: O(V)
// Tested:
// Stress Tested
// https://cses.fi/problemset/task/1669
struct Cycle {
int V; vector<bool> vis; vector<int> to, cycle;
template <class Graph> void dfs(const Graph &G, int v, int prev) {
vis[v] = true; for (int w : G[v]) {
if (!vis[w]) dfs(G, w, to[w] = v);
else if (w != prev) {
for (int x = v; x != w; x = to[x]) cycle.push_back(x);
cycle.push_back(w); cycle.push_back(v);
}
if (!cycle.empty()) return;
}
}
template <class Graph>
Cycle(const Graph &G) : V(G.size()), vis(V, false), to(V) {
for (int v = 0; v < V; v++) {
for (int w : G[v]) {
if (v == w) { cycle.push_back(v); cycle.push_back(v); return; }
if (vis[w]) {
cycle.push_back(v); cycle.push_back(w); cycle.push_back(v); return;
}
}
for (int w : G[v]) vis[w] = false;
}
fill(vis.begin(), vis.end(), false);
for (int v = 0; v < V && cycle.empty(); v++) if (!vis[v]) dfs(G, v, -1);
}
};
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Finds an Eulerian walk (or a circuit) in a graph which can be
// either undirected or directed
// A undirected walk exists iff every exactly zero of two vertices has an odd
// degree and all nonzero degree vertices are in a single connected component
// A undirected circuit exists iff every vertex has an even degree
// and all nonzero degree vertices are in a single connected component
// A directed walk exists iff at most one vertex has outDeg - inDeg = 1 and at
// most one vertex has inDeg - outDeg = 1, with all other vertices having
// inDeg = outDeg and all vertices all nonzero degree vertices are in a
// single connected component of the underlying undirected graph
// A directed circuit exists iff all vertices have inDeg = outDeg and all
// nonzero degree vertices are in a single strongly connected component
// Vertices are 0-indexed
// Function Arguments:
// V: number of vertices in the graph
// edges: a vector of pairs in the form (v, w) representing
// an edge in the simple graph between vertices v and w, each edge should
// be specified exactly once regardless of whether the graph is
// directed or undirected
// directed: a boolean indicating whether the graph is directed or not
// circuit: a boolean indicating whether the Eulerian walk is required to be
// a circuit (first vertex equal to last)
// s: the starting vertex of the Eulerian walk, or -1 if any vertex can be
// the starting vertex
// Return Value: the vertices in the Eulerian walk with the first vertex
// either equal to s if s is non negative, or any arbitrary vertex if
// s is -1, and the last vertex equal to the first vertex if circuit is true,
// and any vertex otherwise
// In practice, has a moderate constant
// Time Complexity: O(V + E)
// Memory Complexity: O(V + E)
// Tested:
// Stress Tested
// https://open.kattis.com/problems/eulerianpath
// https://cses.fi/problemset/task/1691/
// https://cses.fi/problemset/task/1693/
vector<int> eulerianWalk(int V, const vector<pair<int, int>> &edges,
bool directed, bool circuit, int s = -1) {
if (V == 0) return vector<int>();
else if (edges.empty()) return vector<int>{0};
vector<int> st(V + 1, 0), d(V, 0), walk; walk.reserve(edges.size() + 1);
vector<int> to(edges.size() * (directed ? 1 : 2)), eInd(to.size());
for (auto &&e : edges) {
st[e.first]++; d[e.second]++;
if (!directed) { st[e.second]++; d[e.first]++; }
}
if (s == -1) {
s = edges[0].first; if (circuit) {}
else if (directed) { for (int v = 0; v < V; v++) if (st[v] > d[v]) s = v; }
else { for (int v = 0; v < V; v++) if (d[v] % 2 == 1) s = v; }
}
partial_sum(st.begin(), st.end(), st.begin()); fill(d.begin(), d.end(), 0);
for (int i = 0, v, w; i < int(edges.size()); i++) {
tie(v, w) = edges[i]; to[--st[v]] = w; eInd[st[v]] = i;
if (!directed) { to[--st[w]] = v; eInd[st[w]] = i; }
}
vector<int> cur = st, stk(edges.size() + 1);
vector<bool> vis(edges.size(), false);
int top = 0; d[stk[top++] = s]++; while (top > 0) {
int v = stk[top - 1];
if (cur[v] == st[v + 1]) { walk.push_back(v); --top; continue; }
int w = to[cur[v]], e = eInd[cur[v]++];
if (!vis[e]) { d[v]--; d[stk[top++] = w]++; vis[e] = true; }
}
if ((circuit && walk[0] != walk.back())
|| walk.size() != edges.size() + 1) return vector<int>();
for (int di : d) if (di < 0) return vector<int>();
reverse(walk.begin(), walk.end()); return walk;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
#pragma once
#include <bits/stdc++.h>
using namespace std;
// Counts the number of 4-cycles in a simple graph
// Vertices are 0-indexed
// Function Arguments:
// V: the number of vertices in the simple graph
// edges: a vector of pairs in the form (v, w) representing
// an undirected edge in the simple graph (no self loops or parallel edges)
// between vertices v and w
// In practice, has a very small constant
// Time Complexity: O(V + E sqrt E)
// Memory Complexity: O(V + E)
// Tested:
// Fuzz and Stress Tested
long long fourCycles(int V, const vector<pair<int, int>> &edges) {
vector<int> st1(V + 1, 0), st2(V + 1, 0), d(V, 0);
vector<int> to1(edges.size()), to2(edges.size());
for (auto &&e : edges) { d[e.first]++; d[e.second]++; }
auto cmp = [&] (int v, int w) { return d[v] == d[w] ? v > w : d[v] > d[w]; };
for (auto &&e : edges) {
int v, w; tie(v, w) = e; if (cmp(v, w)) swap(v, w);
st1[v]++; st2[w]++;
}
partial_sum(st1.begin(), st1.end(), st1.begin());
partial_sum(st2.begin(), st2.end(), st2.begin()); for (auto &&e : edges) {
int v, w; tie(v, w) = e; if (cmp(v, w)) swap(v, w);
to1[--st1[v]] = w; to2[--st2[w]] = v;
}
#define loop(h) for (int e1 = st##h[v]; e1 < st##h[v + 1]; e1++) \
for (int w = to##h[e1], e2 = st1[w]; e2 < st1[w + 1]; e2++)
long long ret = 0; vector<long long> cnt(V, 0); for (int v = 0; v < V; v++) {
loop(1) if (cmp(to1[e2], v)) ret += cnt[to1[e2]]++;
loop(2) if (cmp(to1[e2], v)) ret += cnt[to1[e2]]++;
loop(1) cnt[to1[e2]] = 0;
loop(2) cnt[to1[e2]] = 0;
}
#undef loop
return ret;
}
| {
"repo_name": "wesley-a-leung/Resources",
"stars": "34",
"repo_language": "C++",
"file_name": "SkewHeapIncremental.h",
"mime_type": "text/x-c++"
} |
Subsets and Splits