Link Search Menu Expand Document
あるまかんライブラリ

:warning: readUndirectedGraph() (無向グラフの入力)
(Util/IO/read-undirected-graph.hpp)

Depends on

Code

#pragma once
#include <cstdint>
#include <iostream>

#include "../../Graph/graph-template.hpp"

/**
 * @brief readUndirectedGraph() (無向グラフの入力)
 */
template <class T>
Graph<T> readUndirectedGraph(size_t V, size_t E, int padding = -1, std::istream& is = std::cin) {
    Graph<T> G(V);
    for (size_t i = 0; i < E; ++i) {
        Edge<T> e;
        is >> e;
        e.from += padding, e.to += padding;
        e.id = static_cast<int>(i);
        G[e.from].emplace_back(e);
        G[e.to].emplace_back(e.rev());
    }
    return G;
}
#line 2 "Util/IO/read-undirected-graph.hpp"
#include <cstdint>
#include <iostream>

#line 3 "Graph/graph-template.hpp"
#include <vector>
#line 5 "Graph/graph-template.hpp"

/**
 * @brief graph-template (Edge, Graph, MatrixGraph)
 */
//! グラフの辺 (重み付き)
template <class T>
struct Edge {
    int from, to;
    T weight;
    int id;

    Edge() = default;

    constexpr explicit Edge(int to_, const T& weight_)
        : Edge(-1, to_, weight_, -1) {}

    constexpr Edge(int from_, int to_, const T& weight_, int id_ = -1)
        : from(from_)
        , to(to_)
        , weight(weight_)
        , id(id_) {}

    constexpr const Edge rev() const { return Edge(to, from, weight, id); }

    template <class Int, std::enable_if_t<std::is_integral<Int>::value, std::nullptr_t> = nullptr>
    constexpr operator Int() const {
        return static_cast<Int>(to);
    }

    friend std::istream& operator>>(std::istream& is, Edge& e) { return is >> e.from >> e.to >> e.weight; }
};

//! グラフの辺 (重みなし)
template <>
struct Edge<void> {
    int from, to;
    int id;

    Edge() = default;

    constexpr explicit Edge(int to_)
        : Edge(-1, to_, -1) {}

    constexpr Edge(int from_, int to_, int id_ = -1)
        : from(from_)
        , to(to_)
        , id(id_) {}

    constexpr const Edge rev() const { return Edge(to, from, id); }

    template <class Int, std::enable_if_t<std::is_integral<Int>::value, std::nullptr_t> = nullptr>
    constexpr operator Int() const {
        return static_cast<Int>(to);
    }

    friend std::istream& operator>>(std::istream& is, Edge& e) { return is >> e.from >> e.to; }
};

template <class T>
using Graph = std::vector<std::vector<Edge<T>>>;
#line 6 "Util/IO/read-undirected-graph.hpp"

/**
 * @brief readUndirectedGraph() (無向グラフの入力)
 */
template <class T>
Graph<T> readUndirectedGraph(size_t V, size_t E, int padding = -1, std::istream& is = std::cin) {
    Graph<T> G(V);
    for (size_t i = 0; i < E; ++i) {
        Edge<T> e;
        is >> e;
        e.from += padding, e.to += padding;
        e.id = static_cast<int>(i);
        G[e.from].emplace_back(e);
        G[e.to].emplace_back(e.rev());
    }
    return G;
}
Back to top page