競技プログラミング用 C++ ライブラリ
test/dynamic_connectivity.test.cpp · GitHub で見る
#define PROBLEM "https://judge.yosupo.jp/problem/dynamic_graph_vertex_add_component_sum"
#include "../graph/dynamic_connectivity.hpp"
#include "../components/fast_io.hpp"
#include <cstdint>
#include <vector>
using namespace std;
int64_t op(int64_t a, int64_t b) { return a + b; }
int64_t e() { return 0; }
int main() {
FastInput input;
FastOutput output;
int n = 0, q = 0;
input.read(n); input.read(q);
vector<int64_t> values(n);
for (auto &v : values) input.read(v);
DynamicConnectivity<int64_t, op, e> graph(values);
graph.reserve(q);
for (int repeat_index = 0; repeat_index < q; ++repeat_index) {
int type = 0, u = 0;
input.read(type); input.read(u);
if (type < 2) {
int v = 0;
input.read(v);
if (type == 0) graph.link(u, v);
else graph.cut(u, v);
} else if (type == 2) {
int64_t x = 0;
input.read(x);
graph.set(u, graph.get(u) + x);
} else output.println(graph.prod(u));
}
}
#line 1 "test/dynamic_connectivity.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/dynamic_graph_vertex_add_component_sum"
#line 1 "graph/dynamic_connectivity.hpp"
#line 1 "components/splitmix64.hpp"
#include <cstdint>
inline std::uint64_t splitmix64(std::uint64_t x) {
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return x ^ (x >> 31);
}
class SplitMix64 {
std::uint64_t state;
public:
explicit SplitMix64(std::uint64_t seed = 0) : state(seed) {}
std::uint64_t operator()() { return splitmix64(state += 0x9e3779b97f4a7c15ULL); }
};
#line 5 "graph/dynamic_connectivity.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cassert>
#include <chrono>
#include <cstddef>
#line 12 "graph/dynamic_connectivity.hpp"
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>
template <class S = void, auto op = nullptr, auto e = nullptr>
class DynamicConnectivity {
static constexpr bool aggregate = !std::is_void_v<S>;
struct Empty {};
using Value = std::conditional_t<aggregate, S, Empty>;
struct alignas(32) Node {
int ch[2] = {}, parent = 0, size = 0, key = 0, aux = 0;
std::uint8_t own = 0, flags = 0;
};
struct Edge {
std::uint64_t key = 0;
int top = 0, count = 0, prev[2] = {}, next[2] = {};
};
int n = 0, groups = 0, active = 0, free_edge = 0, free_arc = 0;
std::int64_t m = 0;
std::uint64_t seed = std::chrono::steady_clock::now().time_since_epoch().count();
std::vector<Node> t;
std::vector<Edge> edges;
std::vector<int> table;
std::vector<std::vector<int>> vertices;
std::vector<Value> values, sums;
static std::uint64_t key(int u, int v) {
if (u > v) std::swap(u, v);
return (std::uint64_t(unsigned(u)) << 32) | unsigned(v);
}
std::uint64_t hash(std::uint64_t x) const { return splitmix64(x + seed); }
int level_of(int id) const {
int x = edges[id].top;
return x > 0 ? (t[x].own >> 3) : -x - 1;
}
int slot(std::uint64_t k) const {
int mask = static_cast<int>(table.size()) - 1, i = hash(k) & mask;
while (table[i] && edges[table[i]].key != k) i = (i + 1) & mask;
return i;
}
void rehash(int capacity) {
table.assign(capacity, 0);
for (int i = 1; i < static_cast<int>(edges.size()); ++i)
if (edges[i].count) table[slot(edges[i].key)] = i;
}
void erase_slot(int i) {
int mask = static_cast<int>(table.size()) - 1;
for (int j = (i + 1) & mask; table[j]; j = (j + 1) & mask) {
int k = hash(edges[table[j]].key) & mask;
if (((j - k) & mask) >= ((j - i) & mask)) table[i] = table[j], i = j;
}
table[i] = 0;
}
void check(int v) const {
assert(0 <= v && v < n);
(void)v;
}
[[gnu::always_inline]] void pull(int x) {
auto &v = t[x];
int l = v.ch[0], r = v.ch[1];
v.size = t[l].size + t[r].size + (v.key > 0);
v.flags = t[l].flags | t[r].flags | (v.own & 3);
if constexpr (aggregate) {
if (v.own & 4) sums[x] = op(op(sums[l], v.key > 0 ? values[v.key - 1] : sums[0]), sums[r]);
}
}
[[gnu::always_inline]] void rotate(int x) {
int p = t[x].parent, g = t[p].parent;
int d = t[p].ch[1] == x, c = t[x].ch[d ^ 1];
if (g) t[g].ch[t[g].ch[1] == p] = x;
t[x].parent = g;
t[p].ch[d] = c;
if (c) t[c].parent = p;
t[x].ch[d ^ 1] = p;
t[p].parent = x;
pull(p);
}
template <bool update = true>
[[gnu::always_inline]] void splay(int x) {
if (!t[x].parent) return;
while (t[x].parent) {
int p = t[x].parent, g = t[p].parent;
if (!g) { rotate(x); break; }
int gg = t[g].parent, d = t[p].ch[1] == x, side = t[g].ch[1] == p;
if (d == side) {
int a = t[p].ch[d ^ 1], b = t[x].ch[d ^ 1];
t[g].ch[d] = a;
if (a) t[a].parent = g;
t[p].ch[d] = b;
if (b) t[b].parent = p;
t[p].ch[d ^ 1] = g;
t[g].parent = p;
t[x].ch[d ^ 1] = p;
t[p].parent = x;
pull(g);
pull(p);
} else {
int a = t[x].ch[d], b = t[x].ch[d ^ 1];
t[p].ch[d] = b;
if (b) t[b].parent = p;
t[g].ch[side] = a;
if (a) t[a].parent = g;
t[x].ch[d] = g;
t[x].ch[d ^ 1] = p;
t[p].parent = t[g].parent = x;
pull(p);
pull(g);
}
t[x].parent = gg;
if (gg) t[gg].ch[t[gg].ch[1] == g] = x;
}
if constexpr (update) pull(x);
}
bool same_nodes(int u, int v) {
if (u == v) return true;
splay(u);
splay(v);
return t[u].parent != 0;
}
bool same_vertices(int u, int v) {
int a = vertices[0][u], b = vertices[0][v];
return a && b && same_nodes(a, b);
}
int join(int a, int b) {
if (!a || !b) return a ? a : b;
int x = a;
while (t[x].ch[1]) x = t[x].ch[1];
splay<false>(x);
t[x].ch[1] = b;
t[b].parent = x;
pull(x);
return x;
}
int reroot(int x) {
splay<false>(x);
int l = t[x].ch[0];
if (!l) {
pull(x);
return x;
}
t[l].parent = t[x].ch[0] = 0;
pull(x);
return join(x, l);
}
int vertex(int level, int v) {
if (level == static_cast<int>(vertices.size())) vertices.emplace_back(n, 0);
int &x = vertices[level][v];
if (!x) {
assert(t.size() < std::size_t(std::numeric_limits<int>::max()));
x = static_cast<int>(t.size());
t.emplace_back();
t[x].key = v + 1;
t[x].size = 1;
if constexpr (aggregate) {
if (level == 0) t[x].own = 4, sums.push_back(values[v]);
else sums.push_back(e());
}
}
return x;
}
int allocate_arcs() {
int x = free_arc;
if (x) {
free_arc = t[x].ch[0];
t[x] = t[x + 1] = Node{};
if constexpr (aggregate) sums[x] = sums[x + 1] = e();
} else {
assert(t.size() <= std::size_t(std::numeric_limits<int>::max() - 2));
x = static_cast<int>(t.size());
t.emplace_back();
t.emplace_back();
if constexpr (aggregate) sums.insert(sums.end(), 2, e());
}
return x;
}
void link_tree(int id, int level, bool exact) {
int u = vertex(level, edges[id].key >> 32), v = vertex(level, unsigned(edges[id].key));
u = reroot(u), v = reroot(v);
int a = allocate_arcs(), b = a + 1;
t[a].key = -id;
t[a].aux = edges[id].top;
t[a].own = (level << 3) | (aggregate && level == 0 ? 4 : 0) | exact;
t[b].own = aggregate && level == 0 ? 4 : 0;
t[a].ch[0] = u, t[a].ch[1] = v;
t[u].parent = t[v].parent = a;
t[a].size = t[u].size + t[v].size;
t[a].flags = t[u].flags | t[v].flags | exact;
if constexpr (aggregate)
if (level == 0) sums[a] = op(sums[u], sums[v]);
t[b].ch[0] = a;
t[a].parent = b;
t[b].size = t[a].size;
t[b].flags = t[a].flags;
if constexpr (aggregate)
if (level == 0) sums[b] = sums[a];
edges[id].top = a;
}
std::pair<int, int> cut_tree(int a) {
int base = a, b = a + 1;
int x = a, y = b;
for (int i = 0; i < 4; ++i) {
if (!t[x].parent) break;
if (!t[y].parent) { std::swap(a, b); break; }
x = t[x].parent;
y = t[y].parent;
}
splay<false>(a);
int l = t[a].ch[0], r = t[a].ch[1];
if (l) t[l].parent = 0;
if (r) t[r].parent = 0;
join(r, l);
splay<false>(b);
l = t[b].ch[0], r = t[b].ch[1];
if (l) t[l].parent = 0;
if (r) t[r].parent = 0;
t[base].ch[0] = free_arc;
free_arc = base;
return {l, r};
}
int find_flag(int x, int flag) {
splay(x);
if (!(t[x].flags & flag)) return 0;
while (!(t[x].own & flag)) {
int l = t[x].ch[0];
x = t[l].flags & flag ? l : t[x].ch[1];
}
splay(x);
return x;
}
void attach(int id, int level) {
for (int side = 0; side < 2; ++side) {
int x = vertex(level, side ? unsigned(edges[id].key) : edges[id].key >> 32);
int old = t[x].aux, token = id * 2 + side;
edges[id].prev[side] = 0;
edges[id].next[side] = old;
if (old) edges[old >> 1].prev[old & 1] = token;
t[x].aux = token;
if (!old) splay<false>(x), t[x].own |= 2, pull(x);
}
edges[id].top = -level - 1;
}
void detach(int id) {
int level = level_of(id);
for (int side = 0; side < 2; ++side) {
int x = vertices[level][side ? unsigned(edges[id].key) : edges[id].key >> 32];
int p = edges[id].prev[side], q = edges[id].next[side];
if (p) edges[p >> 1].next[p & 1] = q;
else
t[x].aux = q;
if (q) edges[q >> 1].prev[q & 1] = p;
if (!t[x].aux) splay<false>(x), t[x].own &= ~2, pull(x);
}
}
bool reconnect(const std::pair<int, int> *roots, int level) {
for (; level >= 0; --level) {
auto [a, b] = roots[level];
if (t[a].size > t[b].size) std::swap(a, b);
if (!(t[a].flags & 2)) continue;
bool promoted = false;
auto replace = [&](int id) {
int u = edges[id].key >> 32, v = unsigned(edges[id].key);
if (same_nodes(vertices[level][u], vertices[level][v])) return false;
detach(id);
edges[id].top = 0;
for (int i = 0; i <= level; ++i) link_tree(id, i, i == level);
return true;
};
while (int x = find_flag(a, 2)) {
while (t[x].aux) {
int id = t[x].aux >> 1;
if (replace(id)) return true;
if (!promoted) {
int token = edges[id].next[t[x].aux & 1];
if (token && replace(token >> 1)) return true;
while (int y = find_flag(a, 1)) {
int edge = -t[y].key;
assert(edges[edge].top == y && level_of(edge) == level);
t[y].own &= ~1;
pull(y);
link_tree(edge, level + 1, true);
}
promoted = true;
}
detach(id);
attach(id, level + 1);
}
}
}
return false;
}
void init(int count) {
assert(0 <= count && count < std::numeric_limits<int>::max() / 3);
n = groups = count;
t.reserve(std::size_t(n) * 3 + 1);
t.resize(1);
vertices.emplace_back(n, 0);
edges.emplace_back();
table.assign(8, 0);
if constexpr (aggregate) {
values.assign(n, e());
sums.reserve(std::size_t(n) * 3 + 1);
sums.assign(1, e());
}
}
public:
explicit DynamicConnectivity(int n = 0) { init(n); }
explicit DynamicConnectivity(const std::vector<Value> &a)
requires aggregate
{
assert(a.size() < std::size_t(std::numeric_limits<int>::max() / 3));
init(static_cast<int>(a.size()));
values = a;
}
void reserve(int capacity) {
assert(0 <= capacity && capacity < std::numeric_limits<int>::max() / 4);
edges.reserve(std::size_t(capacity) + 1);
int buckets = std::bit_ceil(unsigned(std::max(8, capacity * 2)));
if (buckets > static_cast<int>(table.size())) rehash(buckets);
}
int size() const { return n; }
int size(int v) {
check(v);
int x = vertices[0][v];
if (!x) return 1;
splay(x);
return t[x].size;
}
int component_count() const { return groups; }
std::int64_t edge_count() const { return m; }
int count(int u, int v) const {
check(u);
check(v);
return edges[table[slot(key(u, v))]].count;
}
bool same(int u, int v) {
check(u);
check(v);
return u == v || groups == 1 || (groups != n && same_vertices(u, v));
}
bool link(int u, int v) {
check(u);
check(v);
std::uint64_t k = key(u, v);
int pos = slot(k), id = table[pos];
++m;
if (id) {
assert(edges[id].count < std::numeric_limits<int>::max());
++edges[id].count;
return false;
}
if ((active + 1) * 2 > static_cast<int>(table.size())) rehash(static_cast<int>(table.size()) * 2), pos = slot(k);
id = free_edge;
if (id)
free_edge = edges[id].next[0], edges[id] = Edge{};
else {
assert(edges.size() < std::size_t(std::numeric_limits<int>::max() / 2));
id = static_cast<int>(edges.size());
edges.emplace_back();
}
table[pos] = id;
edges[id].key = k;
edges[id].count = 1;
++active;
if (u == v) return false;
if (groups != 1 && !same_vertices(u, v)) {
link_tree(id, 0, true);
--groups;
return true;
}
attach(id, 0);
return false;
}
bool cut(int u, int v) {
check(u);
check(v);
int pos = slot(key(u, v)), id = table[pos];
if (!id) return false;
--m;
if (--edges[id].count) return false;
erase_slot(pos);
--active;
bool split = false;
if (edges[id].top > 0) {
int a = edges[id].top;
int level = level_of(id), i = level;
std::array<std::pair<int, int>, 32> roots;
while (a) {
int down = t[a].aux;
roots[i--] = cut_tree(a);
a = down;
}
split = !reconnect(roots.data(), level);
groups += split;
} else if (u != v)
detach(id);
edges[id].next[0] = free_edge;
free_edge = id;
return split;
}
Value get(int v) const
requires aggregate
{
check(v);
return values[v];
}
void set(int v, Value value)
requires aggregate
{
check(v);
int x = vertices[0][v];
if (x) splay<false>(x);
values[v] = std::move(value);
if (x) pull(x);
}
Value prod(int v)
requires aggregate
{
check(v);
int x = vertices[0][v];
if (!x) return values[v];
splay(x);
return sums[x];
}
};
#line 1 "components/fast_io.hpp"
#line 8 "components/fast_io.hpp"
#include <charconv>
#line 11 "components/fast_io.hpp"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#line 18 "components/fast_io.hpp"
#if defined(__unix__) || defined(__APPLE__)
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace fast_io_detail { struct BulkInput; struct BulkOutput; }
class FastInput {
friend struct fast_io_detail::BulkInput;
static constexpr std::size_t capacity = 1 << 16;
FILE *file = nullptr;
std::unique_ptr<char[]> buffer;
const char *current = "", *end = current;
std::string scratch;
void *mapping = nullptr;
std::size_t mapped_size = 0;
bool refill() {
if (!file) return false;
std::size_t n = std::fread(buffer.get(), 1, capacity, file);
current = buffer.get();
end = current + n;
return n;
}
static const char *scan(const char *p, const char *end) {
while (end - p >= 8) {
std::uint64_t x;
std::memcpy(&x, p, 8);
if ((x - 0x2121212121212121ULL) & ~x & 0x8080808080808080ULL) break;
p += 8;
}
while (p != end && static_cast<unsigned char>(*p) > ' ') ++p;
return p;
}
public:
explicit FastInput(FILE *input = stdin) {
#if defined(__unix__) || defined(__APPLE__)
struct stat status;
int fd = fileno(input);
auto offset = ftello(input);
if (fd >= 0 && offset >= 0 && !fstat(fd, &status) && S_ISREG(status.st_mode) && status.st_size > offset) {
mapped_size = status.st_size;
mapping = mmap(nullptr, mapped_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapping != MAP_FAILED) {
current = static_cast<const char *>(mapping) + offset;
end = static_cast<const char *>(mapping) + mapped_size;
return;
}
mapping = nullptr;
}
#endif
file = input;
buffer = std::make_unique_for_overwrite<char[]>(capacity);
}
explicit FastInput(std::string_view input) : current(input.empty() ? "" : input.data()), end(current + input.size()) {}
FastInput(const FastInput &) = delete;
FastInput &operator=(const FastInput &) = delete;
~FastInput() {
#if defined(__unix__) || defined(__APPLE__)
if (mapping) munmap(mapping, mapped_size);
#endif
}
std::string_view token() {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return {};
}
const char *begin = current;
current = scan(current, end);
if (current != end || !file) return {begin, std::size_t(current - begin)};
scratch.assign(begin, end);
while (refill()) {
current = scan(current, end);
scratch.append(buffer.get(), std::size_t(current - buffer.get()));
if (current != end) break;
}
return scratch;
}
template <class T>
bool read(T &value) {
if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return false;
}
if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4 && std::endian::native == std::endian::little) {
if (end - current >= 11) {
std::uint64_t x;
std::memcpy(&x, current, 8);
if (!(((x + 0x4646464646464646ULL) | (x - 0x3030303030303030ULL)) & 0x8080808080808080ULL)) {
x &= 0x0f0f0f0f0f0f0f0fULL;
x = (x * 10 + (x >> 8)) & 0x00ff00ff00ff00ffULL;
x = (x * 100 + (x >> 16)) & 0x0000ffff0000ffffULL;
std::uint64_t v = std::uint32_t(x * 10000 + (x >> 32));
int n = 8;
for (; n < 10 && static_cast<unsigned char>(current[n]) - unsigned('0') < 10; ++n)
v = v * 10 + (current[n] - '0');
if (static_cast<unsigned char>(current[n]) <= ' ' && v <= 0xffffffffULL) {
current += n;
value = T(v);
return true;
}
}
}
}
T parsed{};
auto result = std::from_chars(current, end, parsed);
if (result.ec == std::errc{} && (result.ptr != end ? static_cast<unsigned char>(*result.ptr) <= ' ' : !file)) {
current = result.ptr;
value = parsed;
return true;
}
}
auto s = token();
if (s.empty()) return false;
if constexpr (std::is_same_v<T, bool>) {
assert(s == "0" || s == "1");
value = s[0] == '1';
} else if constexpr (std::is_integral_v<T>) {
auto result = std::from_chars(s.data(), s.data() + s.size(), value);
assert(result.ec == std::errc{} && result.ptr == s.data() + s.size());
(void)result;
} else value = T(s);
return true;
}
};
class FastOutput {
friend struct fast_io_detail::BulkOutput;
inline static constexpr auto quads = [] {
std::array<std::array<char, 4>, 10000> table{};
for (int i = 0; i < 10000; ++i)
table[i] = {char('0' + i / 1000), char('0' + i / 100 % 10), char('0' + i / 10 % 10), char('0' + i % 10)};
return table;
}();
FILE *file;
std::unique_ptr<char[]> buffer = std::make_unique_for_overwrite<char[]>(1 << 16);
std::size_t capacity = 1 << 16, length = 0;
char *reserve(std::size_t n) {
if (n > capacity - length) {
if (!flush()) throw std::runtime_error("output failed");
if (n > capacity) {
std::size_t next = std::max(n, 2 * capacity);
buffer = std::make_unique_for_overwrite<char[]>(next);
capacity = next;
}
}
return buffer.get() + length;
}
public:
explicit FastOutput(FILE *output = stdout) : file(output) {}
FastOutput(const FastOutput &) = delete;
FastOutput &operator=(const FastOutput &) = delete;
~FastOutput() { flush(); }
bool flush() {
std::size_t offset = 0;
while (offset < length) {
auto n = std::fwrite(buffer.get() + offset, 1, length - offset, file);
if (!n) {
std::memmove(buffer.get(), buffer.get() + offset, length - offset);
length -= offset;
return false;
}
offset += n;
}
length = 0;
return std::fflush(file) == 0;
}
void write(char c) { *reserve(1) = c; ++length; }
void write(__uint128_t value) {
char digits[40];
char *end = digits + sizeof(digits), *begin = end;
do { *--begin = char('0' + value % 10); value /= 10; } while (value);
write(std::string_view(begin, end - begin));
}
void write(__int128_t value) {
__uint128_t magnitude = __uint128_t(value);
if (value < 0) write('-'), magnitude = 0 - magnitude;
write(magnitude);
}
void write(std::string_view s) {
char *out = reserve(s.size());
if (!s.empty()) std::memcpy(out, s.data(), s.size());
length += s.size();
}
template <class T> requires std::is_integral_v<T>
void write(T value) {
char *out = reserve(32);
if constexpr (std::is_same_v<T, bool>) *out = '0' + value, ++length;
else if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4) {
char *p = out;
if (value >= 100000000) {
auto high = value / 100000000, low = value % 100000000;
p = std::to_chars(p, p + 2, high).ptr;
std::memcpy(p, quads[low / 10000].data(), 4);
std::memcpy(p + 4, quads[low % 10000].data(), 4);
p += 8;
} else if (value >= 10000) {
p = std::to_chars(p, p + 4, value / 10000).ptr;
std::memcpy(p, quads[value % 10000].data(), 4);
p += 4;
} else p = std::to_chars(p, p + 4, value).ptr;
length += p - out;
} else length += std::to_chars(out, out + 32, value).ptr - out;
}
template <class T> requires requires(const T &value, char *out) { value.decimal_capacity(); value.to_chars(out); }
void write(const T &value) {
char *out = reserve(value.decimal_capacity());
length += value.to_chars(out) - out;
}
template <class T>
void println(const T &value) { write(value); write('\n'); }
};
#line 6 "test/dynamic_connectivity.test.cpp"
using namespace std;
int64_t op(int64_t a, int64_t b) { return a + b; }
int64_t e() { return 0; }
int main() {
FastInput input;
FastOutput output;
int n = 0, q = 0;
input.read(n); input.read(q);
vector<int64_t> values(n);
for (auto &v : values) input.read(v);
DynamicConnectivity<int64_t, op, e> graph(values);
graph.reserve(q);
for (int repeat_index = 0; repeat_index < q; ++repeat_index) {
int type = 0, u = 0;
input.read(type); input.read(u);
if (type < 2) {
int v = 0;
input.read(v);
if (type == 0) graph.link(u, v);
else graph.cut(u, v);
} else if (type == 2) {
int64_t x = 0;
input.read(x);
graph.set(u, graph.get(u) + x);
} else output.println(graph.prod(u));
}
}