競技プログラミング用 C++ ライブラリ
test/functional_graph_jump.test.cpp · GitHub で見る
#define PROBLEM "https://judge.yosupo.jp/problem/jump_on_tree"
#include "graph/functional_graph.hpp"
#include "components/fast_io.hpp"
int main() {
FastInput input;
FastOutput output;
int n = 0, q = 0;
input.read(n);
input.read(q);
std::vector<std::vector<int>> graph(n);
for (int i = 1; i < n; ++i) {
int u = 0, v = 0;
input.read(u);
input.read(v);
graph[u].push_back(v);
graph[v].push_back(u);
}
std::vector<int> next(n, -1), order{0};
next[0] = 0;
for (std::size_t i = 0; i < order.size(); ++i) {
int v = order[i];
for (int u : graph[v]) if (u != next[v]) next[u] = v, order.push_back(u);
}
FunctionalGraph tree(std::move(next));
while (q--) {
int u = 0, v = 0, k = 0;
input.read(u);
input.read(v);
input.read(k);
int w = tree.lca(u, v), a = tree.depth[u] - tree.depth[w], b = tree.depth[v] - tree.depth[w];
int answer = k > a + b ? -1 : k <= a ? tree.jump(u, k) : tree.jump(v, a + b - k);
output.write(answer);
output.write('\n');
}
}
#line 1 "test/functional_graph_jump.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/jump_on_tree"
#line 1 "graph/functional_graph.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <utility>
#include <vector>
class FunctionalGraph {
std::vector<int> head_, in_, order_, cycle_vertices_, cycle_offsets_;
void check([[maybe_unused]] int v) const { assert(0 <= v && v < size()); }
public:
std::vector<int> to, parent, cycle_id, cycle_position, entry, depth, subtree_size;
FunctionalGraph() = default;
explicit FunctionalGraph(std::vector<int> next) { build(std::move(next)); }
void build(std::vector<int> next) {
assert(next.size() <= std::size_t(std::numeric_limits<int>::max()));
const int n = static_cast<int>(next.size());
for ([[maybe_unused]] int v : next) assert(0 <= v && v < n);
to = std::move(next);
parent.resize(n);
cycle_id.assign(n, -1);
cycle_position.assign(n, -1);
entry.resize(n);
depth.assign(n, 0);
subtree_size.assign(n, 1);
head_.resize(n);
in_.resize(n);
order_.resize(n);
cycle_vertices_.clear();
cycle_offsets_.clear();
std::vector<int> indegree(n), heavy(n, -1), peeled;
peeled.reserve(n);
for (int v : to) ++indegree[v];
for (int v = 0; v < n; ++v) if (!indegree[v]) peeled.push_back(v);
for (std::size_t i = 0; i < peeled.size(); ++i) {
int v = peeled[i], p = to[v];
parent[v] = p;
subtree_size[p] += subtree_size[v];
if (heavy[p] == -1 || subtree_size[heavy[p]] < subtree_size[v]) heavy[p] = v;
if (!--indegree[p]) peeled.push_back(p);
}
cycle_vertices_.reserve(std::size_t(n) - peeled.size());
int position = 0;
for (int v = 0; v < n; ++v) if (indegree[v] && cycle_id[v] == -1) {
int id = cycle_count(), start = static_cast<int>(cycle_vertices_.size()), u = v;
cycle_offsets_.push_back(start);
do {
cycle_id[u] = id;
cycle_position[u] = static_cast<int>(cycle_vertices_.size()) - start;
cycle_vertices_.push_back(u);
entry[u] = u;
parent[u] = -1;
head_[u] = u;
in_[u] = position;
position += subtree_size[u];
order_[u] = position;
u = to[u];
} while (u != v);
}
assert(position == n);
for (auto it = peeled.rbegin(); it != peeled.rend(); ++it) {
int v = *it, p = to[v];
cycle_id[v] = cycle_id[p];
entry[v] = entry[p];
depth[v] = depth[p] + 1;
if (heavy[p] == v) in_[v] = in_[p] + 1, head_[v] = head_[p];
else in_[v] = order_[p] -= subtree_size[v], head_[v] = v;
order_[v] = in_[v] + subtree_size[v];
}
for (int v = 0; v < n; ++v) order_[in_[v]] = v;
}
int size() const { return static_cast<int>(to.size()); }
bool empty() const { return to.empty(); }
int cycle_count() const { return static_cast<int>(cycle_offsets_.size()); }
std::span<const int> cycle(int id) const {
assert(0 <= id && id < cycle_count());
int start = cycle_offsets_[id];
int end = id + 1 < cycle_count() ? cycle_offsets_[id + 1] : static_cast<int>(cycle_vertices_.size());
return std::span<const int>(cycle_vertices_).subspan(start, end - start);
}
int cycle_length(int v) const {
check(v);
return static_cast<int>(cycle(cycle_id[v]).size());
}
bool on_cycle(int v) const {
check(v);
return depth[v] == 0;
}
bool same_component(int u, int v) const {
check(u), check(v);
return cycle_id[u] == cycle_id[v];
}
int reachable_count(int v) const {
check(v);
return depth[v] + cycle_length(v);
}
int jump(int v, std::uint64_t k) const {
check(v);
if (k < std::uint64_t(depth[v])) {
int target = depth[v] - static_cast<int>(k);
while (depth[head_[v]] > target) v = to[head_[v]];
return order_[in_[v] - (depth[v] - target)];
}
k -= depth[v];
v = entry[v];
auto vertices = cycle(cycle_id[v]);
std::size_t position = cycle_position[v] + k % vertices.size();
if (position >= vertices.size()) position -= vertices.size();
return vertices[position];
}
int dist(int u, int v) const {
if (!same_component(u, v)) return -1;
if (depth[v]) return in_[v] <= in_[u] && in_[u] < in_[v] + subtree_size[v] ? depth[u] - depth[v] : -1;
int offset = cycle_position[v] - cycle_position[entry[u]];
if (offset < 0) offset += cycle_length(v);
return depth[u] + offset;
}
int lca(int u, int v) const {
check(u), check(v);
if (entry[u] != entry[v]) return -1;
while (head_[u] != head_[v]) {
if (depth[head_[u]] < depth[head_[v]]) std::swap(u, v);
u = to[head_[u]];
}
return depth[u] < depth[v] ? u : v;
}
std::pair<int, int> subtree(int v) const {
check(v);
return {in_[v], in_[v] + subtree_size[v]};
}
int vertex_at(int position) const {
assert(0 <= position && position < size());
return order_[position];
}
std::vector<std::vector<int>> forest() const {
std::vector<std::vector<int>> result(size());
for (int v = 0; v < size(); ++v) if (parent[v] != -1) {
result[v].push_back(parent[v]);
result[parent[v]].push_back(v);
}
return result;
}
};
#line 1 "components/fast_io.hpp"
#line 5 "components/fast_io.hpp"
#include <array>
#include <bit>
#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>
#include <type_traits>
#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 4 "test/functional_graph_jump.test.cpp"
int main() {
FastInput input;
FastOutput output;
int n = 0, q = 0;
input.read(n);
input.read(q);
std::vector<std::vector<int>> graph(n);
for (int i = 1; i < n; ++i) {
int u = 0, v = 0;
input.read(u);
input.read(v);
graph[u].push_back(v);
graph[v].push_back(u);
}
std::vector<int> next(n, -1), order{0};
next[0] = 0;
for (std::size_t i = 0; i < order.size(); ++i) {
int v = order[i];
for (int u : graph[v]) if (u != next[v]) next[u] = v, order.push_back(u);
}
FunctionalGraph tree(std::move(next));
while (q--) {
int u = 0, v = 0, k = 0;
input.read(u);
input.read(v);
input.read(k);
int w = tree.lca(u, v), a = tree.depth[u] - tree.depth[w], b = tree.depth[v] - tree.depth[w];
int answer = k > a + b ? -1 : k <= a ? tree.jump(u, k) : tree.jump(v, a + b - k);
output.write(answer);
output.write('\n');
}
}