Asa's CP Library

a01sa01to's competitive programming library. Requires C++20 or higher with GCC. This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub a01sa01to/cp-library

:heavy_check_mark: tests/graph/cycle/libchecker-undirected.test.cpp

Depends on

Code

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)
using ll = long long;
using ull = unsigned long long;

#include "../../../library/data-structure/graph.hpp"
#include "../../../library/fastio.hpp"
#include "../../../library/graph/cycle.hpp"
#define PROBLEM "https://judge.yosupo.jp/problem/cycle_detection_undirected"

int main() {
  int n, m;
  asalib::FastIO >> n >> m;
  asalib::graph::graph Graph(n);
  rep(i, m) {
    int u, v;
    asalib::FastIO >> u >> v;
    Graph.add_edge(u, v);
  }
  auto cycle = Graph.cycle();
  if (cycle) {
    auto [vs, es] = *cycle;
    asalib::FastIO << es.size() << '\n';
    rep(i, vs.size()) asalib::FastIO << vs[i] << " \n"[i == vs.size() - 1];
    rep(i, es.size()) asalib::FastIO << es[i] << " \n"[i == es.size() - 1];
  }
  else {
    asalib::FastIO << -1 << '\n';
  }
  return 0;
}
#line 1 "tests/graph/cycle/libchecker-undirected.test.cpp"
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)
using ll = long long;
using ull = unsigned long long;

#line 2 "library/data-structure/graph.hpp"

#line 5 "library/data-structure/graph.hpp"
#include <optional>
#line 8 "library/data-structure/graph.hpp"
using namespace std;

#line 2 "library/_internal/graph-base.hpp"

#include <concepts>
#line 5 "library/_internal/graph-base.hpp"
#include <type_traits>
#line 8 "library/_internal/graph-base.hpp"
using namespace std;

namespace asalib {
  namespace _internal {
    class graph_base {};
    class notweighted_graph_base: public graph_base {};
    class weighted_graph_base: public graph_base {};

    template<typename T>
    concept is_graph = is_base_of_v<graph_base, T>;

    template<typename T>
    concept notweighted_graph = is_base_of_v<notweighted_graph_base, T>;

    template<typename T>
    concept weighted_graph = is_base_of_v<weighted_graph_base, T>;

    using adjlist_t = vector<vector<pair<size_t, size_t>>>;
    using edgelist_t = vector<pair<size_t, size_t>>;
  }  // namespace _internal
}  // namespace asalib
#line 11 "library/data-structure/graph.hpp"

namespace asalib {
  namespace graph {
    class graph: public _internal::notweighted_graph_base {
      public:
      graph(): n_vertex(0), n_edge(0) {}
      explicit graph(size_t n_vertex): n_vertex(n_vertex), n_edge(0) {
        adj_list.reserve(n_vertex);
        adj_list.resize(n_vertex);
      }

      void add_edge(size_t v1, size_t v2) {
        assert(0 <= v1 && v1 < n_vertex);
        assert(0 <= v2 && v2 < n_vertex);
        adj_list[v1].push_back({ v2, n_edge });
        adj_list[v2].push_back({ v1, n_edge });
        edge_list.push_back({ v1, v2 });
        ++n_edge;
      }

      // (v1, v2)
      pair<size_t, size_t> get_edge(size_t edgeId) const {
        assert(0 <= edgeId && edgeId < n_edge);
        return edge_list[edgeId];
      }

      // (v2, edgeId)
      vector<pair<size_t, size_t>> get_adj(size_t vertex) const {
        assert(0 <= vertex && vertex < n_vertex);
        return adj_list[vertex];
      }

      // ---------- prototype ---------- //
      optional<pair<vector<size_t>, vector<size_t>>> cycle() const;
      bool is_connected() const;
      optional<pair<vector<size_t>, vector<size_t>>> eulerian_walk() const;

      private:
      size_t n_vertex, n_edge;
      asalib::_internal::adjlist_t adj_list;
      asalib::_internal::edgelist_t edge_list;
    };
  }  // namespace graph
}  // namespace asalib
#line 2 "library/fastio.hpp"

#line 12 "library/fastio.hpp"
using namespace std;

// TODO: 何も入力がない場合にも対応する?

namespace asalib {
  namespace _internal {
    class FastIO {
      private:
      using uint = unsigned int;
      static constexpr uint BUFFER_SIZE = 1 << 20;
      static constexpr uint MAX_TOKEN_SIZE = 64;

      // ===== Read ===== //

      private:
      array<char, BUFFER_SIZE> read_buffer;
      array<char, BUFFER_SIZE>::iterator read_ptr;
      uint read_size = 0;

      inline void load() {
        // まだ読んでないデータを前に持ってくる
        memcpy(read_buffer.begin(), read_ptr, read_size - (read_ptr - read_buffer.begin()));
        read_size -= read_ptr - read_buffer.begin();
        read_ptr = read_buffer.begin();
        // stdin から読み込み
        read_size += fread(read_buffer.begin() + read_size, 1, BUFFER_SIZE - read_size, stdin);
      }

      inline void skip_space() {
        // 制御文字 + space
        // DEL (127 = 0x7F) がコーナーケースだがまあ使わんやろ
        while (*read_ptr <= ' ') ++read_ptr;
      }

      template<typename T>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      inline void _read_uint(T& x) {
        x = 0;
        while (true) {
          uint64_t v;
          memcpy(&v, read_ptr, 8);
          // '0' -> 0 処理
          // こっちを先にやることで制御文字系もはじく
          v -= 0x30'30'30'30'30'30'30'30;
          // ASCII 範囲外
          if (v & 0x80'80'80'80'80'80'80'80) break;
          // 桁ごとの数字から数値に
          v = (v * 10 + (v >> 8)) & 0x00ff00ff00ff00ff;
          v = (v * 100 + (v >> 16)) & 0x0000ffff0000ffff;
          v = (v * 10000 + (v >> 32)) & 0x00000000ffffffff;
          x = 1'0000'0000 * x + v;
          read_ptr += 8;
        }
        while (true) {
          uint32_t v;
          memcpy(&v, read_ptr, 4);
          v -= 0x30'30'30'30;
          if (v & 0x80'80'80'80) break;
          v = (v * 10 + (v >> 8)) & 0x00ff00ff;
          v = (v * 100 + (v >> 16)) & 0x0000ffff;
          x = 1'0000 * x + v;
          read_ptr += 4;
        }
        while (true) {
          uint16_t v;
          memcpy(&v, read_ptr, 2);
          v -= 0x3030;
          if (v & 0x8080) break;
          v = (v * 10 + (v >> 8)) & 0x00ff;
          x = 100 * x + v;
          read_ptr += 2;
        }
        if (*read_ptr > ' ') x = 10 * x + (*read_ptr++ & 0x0f);
      }

      inline void read_commonop() {
        // そろそろ限界なら読み込み
        if ((read_ptr - read_buffer.begin()) + MAX_TOKEN_SIZE >= BUFFER_SIZE) load();
        skip_space();
      }

      public:
      FastIO& operator>>(char& x) {
        read_commonop();
        x = *read_ptr++;
        return *this;
      }

      FastIO& operator>>(string& x) {
        read_commonop();
        x.clear();
        while (*read_ptr > ' ') {
          x += *read_ptr++;
          if (read_ptr == read_buffer.end()) load();
        }
        return *this;
      }

      template<typename T>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      FastIO& operator>>(T& x) {
        read_commonop();
        constexpr bool is_signed = is_signed_v<T> || is_same_v<T, __int128_t>;
        if constexpr (is_signed) {
          if (*read_ptr == '-') {
            ++read_ptr;
            _read_uint(x);
            x = -x;
            return *this;
          }
        }
        _read_uint(x);
        return *this;
      }

      // ===== Write ===== //

      private:
      array<char, BUFFER_SIZE> write_buffer;
      array<char, BUFFER_SIZE>::iterator write_ptr;
      static constexpr uint MAX_PRECOMPUTE_NUM = 1'0000;
      static constexpr uint MAX_PRECOMPUTE_NUM_DIGIT = 4;

      static constexpr array<char, MAX_PRECOMPUTE_NUM * MAX_PRECOMPUTE_NUM_DIGIT> digits = [] {
        array<char, MAX_PRECOMPUTE_NUM * MAX_PRECOMPUTE_NUM_DIGIT> digits {};
        for (uint i = 0; i < MAX_PRECOMPUTE_NUM; ++i) {
          uint x = i;
          for (int j = MAX_PRECOMPUTE_NUM_DIGIT - 1; j >= 0; --j) {
            digits[i * MAX_PRECOMPUTE_NUM_DIGIT + j] = '0' + (x % 10);
            x /= 10;
          }
        }
        return digits;
      }();

      template<typename T>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      static constexpr array<T, numeric_limits<T>::digits10 + 1> Pow10 = [] {
        array<T, numeric_limits<T>::digits10 + 1> pow10 {};
        pow10[0] = 1;
        for (uint i = 1; i < pow10.size(); ++i) pow10[i] = pow10[i - 1] * 10;
        return pow10;
      }();

      inline void write_commonop() {
        // そろそろ限界なら書き込む
        if ((write_ptr - write_buffer.begin()) + MAX_TOKEN_SIZE >= BUFFER_SIZE) flush();
      }

      inline void putchar(const char& x) { *write_ptr++ = x; }

      template<typename T, int NumDig>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      inline void _write_uint_top(const T& x) {
        // leading-zero を書き込まないようにする
        if constexpr (NumDig > 1) {
          if (x < Pow10<T>[NumDig - 1]) {
            _write_uint_top<T, NumDig - 1>(x);
            return;
          }
        }
        copy_n(digits.begin() + (x + 1) * MAX_PRECOMPUTE_NUM_DIGIT - NumDig, NumDig, write_ptr);
        write_ptr += NumDig;
      }

      template<typename T, int NumDig>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      inline void _write_uint(const T& x) {
        if constexpr (NumDig >= 0) {
          if constexpr (NumDig > MAX_PRECOMPUTE_NUM_DIGIT) _write_uint<T, NumDig - MAX_PRECOMPUTE_NUM_DIGIT>(x / MAX_PRECOMPUTE_NUM);
          copy_n(digits.begin() + x % MAX_PRECOMPUTE_NUM * MAX_PRECOMPUTE_NUM_DIGIT, MAX_PRECOMPUTE_NUM_DIGIT, write_ptr);
          write_ptr += MAX_PRECOMPUTE_NUM_DIGIT;
        }
      }

      template<typename T, int NumDig>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      inline void _write_uint_root(const T& x) {
        if constexpr (is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>) {
          // 128bit 除算はおそいので 64bit 除算を使う
          if (x < Pow10<T>[16]) {
            _write_uint_root<uint64_t, NumDig>(x);
          }
          else if (x < Pow10<T>[32]) {
            _write_uint_root<uint64_t, NumDig>(x / Pow10<T>[16]);
            _write_uint<uint64_t, 16>(x % Pow10<T>[16]);
          }
          else {
            _write_uint_root<uint64_t, NumDig>(x / Pow10<T>[32]);
            _write_uint<uint64_t, 16>(x % Pow10<T>[32] / Pow10<T>[16]);
            _write_uint<uint64_t, 16>(x % Pow10<T>[16]);
          }
          return;
        }

        if constexpr (NumDig < numeric_limits<T>::digits10) {
          if (x >= Pow10<T>[NumDig]) {
            _write_uint_root<T, NumDig + MAX_PRECOMPUTE_NUM_DIGIT>(x);
            return;
          }
        }
        _write_uint_top<T, MAX_PRECOMPUTE_NUM_DIGIT>(x / Pow10<T>[NumDig - MAX_PRECOMPUTE_NUM_DIGIT]);
        if constexpr (NumDig > MAX_PRECOMPUTE_NUM_DIGIT) _write_uint<T, NumDig - MAX_PRECOMPUTE_NUM_DIGIT>(x % Pow10<T>[NumDig - MAX_PRECOMPUTE_NUM_DIGIT]);
      }

      public:
      inline void flush() {
        fwrite(write_buffer.begin(), 1, write_ptr - write_buffer.begin(), stdout);
        write_ptr = write_buffer.begin();
      }

      FastIO& operator<<(const char& x) {
        write_commonop();
        putchar(x);
        return *this;
      }

      FastIO& operator<<(const string& x) {
        write_commonop();
        uint idx = 0;
        while (idx < x.size()) {
          const uint siz = min(BUFFER_SIZE - (uint) (write_ptr - write_buffer.begin()), (uint) x.size() - idx);
          copy_n(x.begin() + idx, siz, write_ptr);
          write_ptr += siz;
          idx += siz;
          if (write_ptr == write_buffer.end()) flush();
        }
        return *this;
      }

      template<typename T>
        requires(integral<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
      FastIO& operator<<(const T& x) {
        write_commonop();
        constexpr bool is_signed = is_signed_v<T> || is_same_v<T, __int128_t>;
        if constexpr (is_signed) {
          if (x < 0) {
            putchar('-');
            _write_uint_root<T, MAX_PRECOMPUTE_NUM_DIGIT>(-x);
            return *this;
          }
        }
        _write_uint_root<T, MAX_PRECOMPUTE_NUM_DIGIT>(x);
        return *this;
      }

      // ===== Common ====== //

      public:
      FastIO() {
        read_ptr = read_buffer.begin();
        write_ptr = write_buffer.begin();
        load();
      }

      ~FastIO() { flush(); }
    };
  }  // namespace _internal

  _internal::FastIO FastIO;
}  // namespace asalib
#line 2 "library/graph/cycle.hpp"

#line 6 "library/graph/cycle.hpp"
using namespace std;

#line 2 "library/_internal/graph/cycle.hpp"

#line 11 "library/_internal/graph/cycle.hpp"
using namespace std;

#line 14 "library/_internal/graph/cycle.hpp"

namespace asalib {
  namespace _internal {
    namespace graph {
      template<bool is_directed>
      optional<pair<vector<size_t>, vector<size_t>>> cycleDetection(const size_t& n_vertex, const size_t& n_edge, const adjlist_t& adj_list, const edgelist_t& edge_list) {
        vector<bool> visited(n_vertex, false);
        vector<bool> finished(n_vertex, false);
        vector<bool> used(n_edge, false);
        stack<size_t> st;
        size_t base_point = -1;

        function<bool(size_t)> dfs = [&](size_t v) -> bool {
          visited[v] = true;
          for (auto [to, edge_id] : adj_list[v]) {
            if (used[edge_id]) continue;
            used[edge_id] = true;
            st.push(edge_id);
            if (!finished[to] && visited[to]) {
              base_point = to;
              return true;
            }
            if (!visited[to] && dfs(to)) return true;
            st.pop();
            used[edge_id] = false;
          }
          finished[v] = true;
          return false;
        };

        for (size_t i = 0; i < n_vertex; ++i) {
          if (!visited[i]) {
            if (dfs(i)) {
              size_t v = base_point;
              vector<size_t> edges, verts;
              while (!st.empty()) {
                size_t edge_id = st.top();
                st.pop();
                edges.push_back(edge_id);
                if constexpr (is_directed) {
                  assert(edge_list[edge_id].second == v);
                  v = edge_list[edge_id].first;
                }
                else {
                  assert(edge_list[edge_id].first == v || edge_list[edge_id].second == v);
                  v = (edge_list[edge_id].first == v ? edge_list[edge_id].second : edge_list[edge_id].first);
                }
                verts.push_back(v);
                if (v == base_point) break;
              }
              reverse(verts.begin(), verts.end());
              reverse(edges.begin(), edges.end());
              assert(verts.size() == edges.size());
              assert(verts[0] == base_point);
              return make_pair(verts, edges);
            }
          }
        }
        return nullopt;
      }
    }  // namespace graph
  }  // namespace _internal
}  // namespace asalib
#line 2 "library/data-structure/digraph.hpp"

#line 8 "library/data-structure/digraph.hpp"
using namespace std;

#line 12 "library/data-structure/digraph.hpp"

namespace asalib {
  namespace graph {
    class digraph: public _internal::notweighted_graph_base {
      public:
      digraph(): n_vertex(0), n_edge(0) {}
      explicit digraph(size_t n_vertex): n_vertex(n_vertex), n_edge(0) {
        adj_list.reserve(n_vertex);
        adj_list.resize(n_vertex);
        adj_list_rev.reserve(n_vertex);
        adj_list_rev.resize(n_vertex);
        underlying_graph = graph(n_vertex);
      }

      void add_edge(size_t from, size_t to) {
        assert(0 <= from && from < n_vertex);
        assert(0 <= to && to < n_vertex);
        adj_list[from].push_back({ to, n_edge });
        adj_list_rev[to].push_back({ from, n_edge });
        edge_list.push_back({ from, to });
        underlying_graph.add_edge(from, to);
        ++n_edge;
      }

      // (from, to)
      pair<size_t, size_t> get_edge(size_t edgeId) const {
        assert(0 <= edgeId && edgeId < n_edge);
        return edge_list[edgeId];
      }

      // (to, edgeId)
      vector<pair<size_t, size_t>> get_adj(size_t vertex) const {
        assert(0 <= vertex && vertex < n_vertex);
        return adj_list[vertex];
      }

      // (from, edgeId)
      vector<pair<size_t, size_t>> get_adjrev(size_t vertex) const {
        assert(0 <= vertex && vertex < n_vertex);
        return adj_list_rev[vertex];
      }

      // ---------- prototype ---------- //
      vector<vector<size_t>> scc() const;
      optional<pair<vector<size_t>, vector<size_t>>> cycle() const;
      bool is_connected() const;
      optional<pair<vector<size_t>, vector<size_t>>> eulerian_walk() const;

      private:
      size_t n_vertex, n_edge;
      asalib::_internal::adjlist_t adj_list, adj_list_rev;
      asalib::_internal::edgelist_t edge_list;
      graph underlying_graph;
    };
  }  // namespace graph
}  // namespace asalib
#line 11 "library/graph/cycle.hpp"

namespace asalib {
  namespace graph {
    optional<pair<vector<size_t>, vector<size_t>>> digraph::cycle() const { return _internal::graph::cycleDetection<true>(n_vertex, n_edge, adj_list, edge_list); }
    optional<pair<vector<size_t>, vector<size_t>>> graph::cycle() const { return _internal::graph::cycleDetection<false>(n_vertex, n_edge, adj_list, edge_list); }
  }  // namespace graph
}  // namespace asalib
#line 10 "tests/graph/cycle/libchecker-undirected.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/cycle_detection_undirected"

int main() {
  int n, m;
  asalib::FastIO >> n >> m;
  asalib::graph::graph Graph(n);
  rep(i, m) {
    int u, v;
    asalib::FastIO >> u >> v;
    Graph.add_edge(u, v);
  }
  auto cycle = Graph.cycle();
  if (cycle) {
    auto [vs, es] = *cycle;
    asalib::FastIO << es.size() << '\n';
    rep(i, vs.size()) asalib::FastIO << vs[i] << " \n"[i == vs.size() - 1];
    rep(i, es.size()) asalib::FastIO << es[i] << " \n"[i == es.size() - 1];
  }
  else {
    asalib::FastIO << -1 << '\n';
  }
  return 0;
}
Back to top page