競技プログラミング用 C++ ライブラリ
test/max_flow_yuki.test.cpp · GitHub で見る
#define PROBLEM "https://yukicoder.me/problems/no/3668"
#include "graph/max_flow.hpp"
#include "components/fast_io.hpp"
int main() {
FastInput input;
FastOutput output;
int n = 0, m = 0, s = 0, t = 0;
input.read(n), input.read(m), input.read(s), input.read(t);
MaxFlow<> graph(n);
graph.reserve(m);
for (int i = 0; i < m; ++i) {
int u = 0, v = 0;
std::int64_t cap = 0;
input.read(u), input.read(v), input.read(cap);
graph.add_edge(u - 1, v - 1, cap);
}
output.println(graph.flow(s - 1, t - 1));
}
#line 1 "test/max_flow_yuki.test.cpp"
#define PROBLEM "https://yukicoder.me/problems/no/3668"
#line 1 "graph/max_flow.hpp"
#line 1 "components/flow_graph.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <limits>
#include <vector>
namespace flow_detail {
template<class Cap> struct Graph {
struct Arc { int to; Cap cap; };
int n;
std::vector<Arc> arcs;
std::vector<int> start, order;
bool built = false;
explicit Graph(int n = 0) : n(n) { assert(n >= 0); }
void reserve(std::size_t m) { assert(m <= std::size_t(std::numeric_limits<int>::max() / 2)); arcs.reserve(2 * m); }
int add_edge(int from, int to, Cap cap) {
assert(0 <= from && from < n && 0 <= to && to < n && cap >= 0);
assert(arcs.size() <= std::size_t(std::numeric_limits<int>::max() - 2));
int id = int(arcs.size());
arcs.push_back({to, cap});
arcs.push_back({from, Cap(0)});
built = false;
return id / 2;
}
void build() {
if (built) return;
start.assign(std::size_t(n) + 1, 0);
for (std::size_t i = 0; i < arcs.size(); ++i) ++start[arcs[i ^ 1].to + 1];
for (int v = 0; v < n; ++v) start[v + 1] += start[v];
order.resize(arcs.size());
auto next = start;
for (int i = 0; i < int(arcs.size()); ++i) order[next[arcs[i ^ 1].to]++] = i;
built = true;
}
void reset_flow() {
for (std::size_t i = 0; i < arcs.size(); i += 2) arcs[i].cap += arcs[i + 1].cap, arcs[i + 1].cap = 0;
}
};
}
#line 1 "components/push_relabel.hpp"
#line 5 "components/push_relabel.hpp"
#include <cstdint>
namespace flow_detail {
template<class Cap> Cap push_relabel(Graph<Cap>& graph, int s, int t) {
graph.build();
int n = graph.n;
assert(n <= std::numeric_limits<int>::max() / 2 - 1);
int dead = 2 * n;
std::vector<__uint128_t> excess(n);
std::vector<int> height(n), current(n), count(std::size_t(dead) + 1), head(std::size_t(dead) + 1, -1), next(n), queue(n);
std::vector<unsigned char> active(n);
int highest = -1;
std::size_t work = 0, threshold = std::max<std::size_t>(1, 4 * graph.arcs.size() + n);
auto activate = [&](int v) {
if (v == s || v == t || active[v] || !excess[v] || height[v] == dead) return;
active[v] = 1;
next[v] = head[height[v]], head[height[v]] = v;
highest = std::max(highest, height[v]);
};
auto buckets = [&] {
std::fill(head.begin(), head.end(), -1);
std::fill(active.begin(), active.end(), 0);
highest = -1;
for (int v = 0; v < n; ++v) activate(v);
};
auto global = [&] {
std::fill(height.begin(), height.end(), n + 1);
std::fill(count.begin(), count.end(), 0);
std::copy_n(graph.start.begin(), n, current.begin());
height[s] = n, height[t] = 0;
int first = 0, last = 0;
queue[last++] = t;
while (first < last) {
int v = queue[first++];
for (int j = graph.start[v]; j < graph.start[v + 1]; ++j) {
int i = graph.order[j], u = graph.arcs[i].to;
if (u != s && height[u] == n + 1 && graph.arcs[i ^ 1].cap) height[u] = height[v] + 1, queue[last++] = u;
}
}
for (int h : height) ++count[h];
buckets();
work = 0;
};
for (int j = graph.start[s]; j < graph.start[s + 1]; ++j) {
int i = graph.order[j];
auto& e = graph.arcs[i];
if (e.to == s || !e.cap) continue;
excess[e.to] += e.cap, graph.arcs[i ^ 1].cap += e.cap, e.cap = 0;
}
global();
while (highest >= 0) {
if (head[highest] < 0) { --highest; continue; }
int v = head[highest];
head[highest] = next[v];
if (!active[v] || height[v] != highest) continue;
active[v] = 0;
while (excess[v] && height[v] < dead) {
if (current[v] == graph.start[v + 1]) {
int old = height[v], value = dead;
for (int j = graph.start[v]; j < graph.start[v + 1]; ++j) {
const auto& e = graph.arcs[graph.order[j]];
if (e.cap) value = std::min(value, height[e.to] + 1);
}
work += graph.start[v + 1] - graph.start[v];
--count[old], ++count[value], height[v] = value, current[v] = graph.start[v];
if (old < n && !count[old]) {
for (int u = 0; u < n; ++u) if (old < height[u] && height[u] < n) {
--count[height[u]], height[u] = n + 1, ++count[n + 1], current[u] = graph.start[u];
}
buckets();
break;
}
} else {
++work;
int i = graph.order[current[v]];
auto& e = graph.arcs[i];
if (!e.cap || height[v] != height[e.to] + 1) { ++current[v]; continue; }
Cap amount = Cap(std::min(excess[v], __uint128_t(e.cap)));
e.cap -= amount, graph.arcs[i ^ 1].cap += amount;
excess[v] -= amount, excess[e.to] += amount;
activate(e.to);
}
}
activate(v);
if (work >= threshold) global();
}
assert(excess[t] <= __uint128_t(std::numeric_limits<Cap>::max()));
return Cap(excess[t]);
}
}
#line 7 "graph/max_flow.hpp"
#include <type_traits>
template<class Cap = std::int64_t> class MaxFlow {
static_assert(std::is_integral_v<Cap> && !std::is_same_v<Cap, bool> && sizeof(Cap) <= 8);
flow_detail::Graph<Cap> graph_;
void vertex([[maybe_unused]] int v) const { assert(0 <= v && v < graph_.n); }
int index(int i) const { assert(0 <= i && std::size_t(i) < graph_.arcs.size() / 2); return 2 * i; }
public:
struct Edge { int from, to; Cap cap, flow; };
explicit MaxFlow(int n = 0) : graph_(n) {}
int size() const { return graph_.n; }
int edge_count() const { return int(graph_.arcs.size() / 2); }
void reserve(std::size_t m) { graph_.reserve(m); }
int add_edge(int from, int to, Cap cap) { return graph_.add_edge(from, to, cap); }
Edge get_edge(int i) const {
int j = index(i);
const auto& a = graph_.arcs[j];
const auto& b = graph_.arcs[j ^ 1];
return {b.to, a.to, Cap(a.cap + b.cap), b.cap};
}
std::vector<Edge> edges() const {
std::vector<Edge> result;
result.reserve(edge_count());
for (int i = 0; i < edge_count(); ++i) result.push_back(get_edge(i));
return result;
}
void change_edge(int i, Cap cap, Cap flow) {
assert(0 <= flow && flow <= cap);
int j = index(i);
graph_.arcs[j].cap = cap - flow, graph_.arcs[j ^ 1].cap = flow;
}
void reset_flow() { graph_.reset_flow(); }
Cap flow(int s, int t) {
vertex(s), vertex(t);
assert(s != t);
return flow_detail::push_relabel(graph_, s, t);
}
Cap flow(int s, int t, Cap limit) {
vertex(s), vertex(t);
assert(s != t && limit >= 0);
graph_.build();
auto& g = graph_;
std::vector<int> level(g.n), iter(g.n), queue(g.n);
struct Frame { int v; Cap limit, sent; };
std::vector<Frame> stack;
stack.reserve(g.n);
Cap total = 0;
while (total < limit) {
std::fill(level.begin(), level.end(), -1);
level[s] = 0;
int head = 0, tail = 0;
queue[tail++] = s;
while (head < tail && level[t] < 0) {
int v = queue[head++];
for (int i = g.start[v]; i < g.start[v + 1]; ++i) {
const auto& e = g.arcs[g.order[i]];
if (!e.cap || level[e.to] >= 0) continue;
level[e.to] = level[v] + 1;
queue[tail++] = e.to;
}
}
if (level[t] < 0) break;
std::copy_n(g.start.begin(), g.n, iter.begin());
stack.push_back({t, Cap(limit - total), Cap(0)});
while (!stack.empty()) {
auto& frame = stack.back();
int v = frame.v;
if (v == s || frame.sent == frame.limit || iter[v] == g.start[v + 1]) {
Cap sent = v == s ? frame.limit : frame.sent;
if (v != s && sent < frame.limit) level[v] = g.n;
stack.pop_back();
if (stack.empty()) { total += sent; break; }
auto& parent = stack.back();
int id = g.order[iter[parent.v]];
g.arcs[id].cap += sent, g.arcs[id ^ 1].cap -= sent;
parent.sent += sent;
if (parent.sent < parent.limit) ++iter[parent.v];
} else {
int id = g.order[iter[v]];
const auto& e = g.arcs[id];
if (level[e.to] < 0 || level[e.to] >= level[v] || !g.arcs[id ^ 1].cap) ++iter[v];
else stack.push_back({e.to, std::min<Cap>(frame.limit - frame.sent, g.arcs[id ^ 1].cap), Cap(0)});
}
}
}
return total;
}
std::vector<bool> min_cut(int s) {
vertex(s);
graph_.build();
std::vector<bool> visited(graph_.n);
std::vector<int> queue{ s };
visited[s] = true;
for (std::size_t head = 0; head < queue.size(); ++head) {
int v = queue[head];
for (int i = graph_.start[v]; i < graph_.start[v + 1]; ++i) {
const auto& e = graph_.arcs[graph_.order[i]];
if (e.cap && !visited[e.to]) visited[e.to] = true, queue.push_back(e.to);
}
}
return visited;
}
};
#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>
#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 4 "test/max_flow_yuki.test.cpp"
int main() {
FastInput input;
FastOutput output;
int n = 0, m = 0, s = 0, t = 0;
input.read(n), input.read(m), input.read(s), input.read(t);
MaxFlow<> graph(n);
graph.reserve(m);
for (int i = 0; i < m; ++i) {
int u = 0, v = 0;
std::int64_t cap = 0;
input.read(u), input.read(v), input.read(cap);
graph.add_edge(u - 1, v - 1, cap);
}
output.println(graph.flow(s - 1, t - 1));
}