跳到正文

算法·理论

【图论模板】日志 (Log)

__zszl__约 27 分钟
原文

这是 2026年1月6日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年1月6日
更新
2026年5月23日
篇幅
约 27 分钟

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1

关联内容

留言:这里是洛谷保存站,如果需要查看,请点击:“刷新内容”,否则可能看到错误信息

日志 (Log)

2026/1/5 20:05 zszl
代码
C++
#define int ll
#include <bits/stdc++.h>
#include <bits/extc++.h>

typedef long long ll;
typedef long double db;
using pii = std::pair<int, int>;
typedef unsigned long long ull;
const int inf = 0x3f3f3f3f3f3f3f3f;

template<typename tpn, typename tpw, typename ten, typename tew>
class Graph {
public:
    struct Edge {
        tpn v;
        tew w;
        ten nxt;
        Edge() : v(0), w(0), nxt(-1) {}
        Edge(tpn _v, tew _w, ten _nxt) : v(_v), w(_w), nxt(_nxt) {}
        
        bool operator==(const Edge& other) const {
            return v == other.v && w == other.w;
        }
        
        bool operator!=(const Edge& other) const {
            return !(*this == other);
        }
    };

    Graph() : m(0) {}

    Graph(tpn n, const tpw& default_weight = tpw{}) : head(n, -1), m(0), node_weights(n, default_weight) {}

    Graph(const Graph& other) {
        *this = other;
    }

    Graph(Graph&& other) noexcept {
        *this = std::move(other);
    }

    Graph& operator=(const Graph& other) {
        if (this != &other) {
            head = other.head;
            edges = other.edges;
            m = other.m;
            node_weights = other.node_weights;
        }
        return *this;
    }

    Graph& operator=(Graph&& other) noexcept {
        if (this != &other) {
            head = std::move(other.head);
            edges = std::move(other.edges);
            m = other.m;
            node_weights = std::move(other.node_weights);
            other.m = 0;
        }
        return *this;
    }

    void resize(tpn n, const tpw& default_weight = tpw{}) {
        tpn old_size = static_cast<tpn>(head.size());
        if (n > old_size) {
            head.resize(n, -1);
            node_weights.resize(n, default_weight);
        } else if (n < old_size) {
            for(int u=0;u<n-1+1;++u) {
                while (head[u] != -1 && edges[head[u]].v >= n) {
                    head[u] = edges[head[u]].nxt;
                }
                ten prev = head[u];
                while (prev != -1 && edges[prev].nxt != -1) {
                    if (edges[edges[prev].nxt].v >= n) {
                        edges[prev].nxt = edges[edges[prev].nxt].nxt;
                    } else {
                        prev = edges[prev].nxt;
                    }
                }
            }
            head.resize(n);
            node_weights.resize(n);
        }
    }

    inline tpn size() const {
        return static_cast<tpn>(head.size());
    }

    void clear() {
        std::fill(head.begin(), head.end(), -1);
        edges.clear();
        m = 0;
    }

    void clear(tpn n, const tpw& default_weight = tpw{}) {
        head.assign(n, -1);
        node_weights.assign(n, default_weight);
        edges.clear();
        m = 0;
    }

    inline void set_node_weight(tpn u, const tpw& weight) {
        if (u >= static_cast<tpn>(node_weights.size())) {
            resize(u + 1);
        }
        node_weights[u] = weight;
    }

    inline tpw get_node_weight(tpn u) const {
        if (u >= static_cast<tpn>(node_weights.size())) {
            throw std::out_of_range("Node index out of bounds");
        }
        return node_weights[u];
    }

    inline Edge addedge(tpn u, tpn v, tew w) {
        if (u >= static_cast<tpn>(head.size()) || v >= static_cast<tpn>(head.size())) {
            tpn new_size = max(u, v) + 1;
            resize(new_size);
        }
        edges.emplace_back(v, w, head[u]);
        head[u] = m++;
        return edges.back();
    }

    inline std::pair<Edge, Edge> addedges(tpn u, tpn v, tew w) {
        if (u >= static_cast<tpn>(head.size()) || v >= static_cast<tpn>(head.size())) {
            tpn new_size = max(u, v) + 1;
            resize(new_size);
        }
        Edge e1 = addedge(u, v, w);
        Edge e2 = addedge(v, u, w);
        return {e1, e2};
    }

    inline bool deledge_by_index(tpn u, ten e) {
        if (u >= static_cast<tpn>(head.size()) || head[u] == -1) return false;
        if (head[u] == e) {
            head[u] = edges[e].nxt;
            return true;
        }
        ten prev = head[u];
        while (prev != -1 && edges[prev].nxt != e) {
            prev = edges[prev].nxt;
        }
        if (prev == -1) return false;
        edges[prev].nxt = edges[e].nxt;
        return true;
    }

    inline bool deledge_by_vertex(tpn u, tpn v) {
        if (u >= static_cast<tpn>(head.size()) || head[u] == -1) return false;
        if (edges[head[u]].v == v) {
            ten e = head[u];
            head[u] = edges[e].nxt;
            return true;
        }
        ten prev = head[u];
        while (prev != -1) {
            if (edges[prev].nxt != -1 && edges[edges[prev].nxt].v == v) {
                ten e = edges[prev].nxt;
                edges[prev].nxt = edges[e].nxt;
                return true;
            }
            prev = edges[prev].nxt;
        }
        return false;
    }

    inline std::pair<bool, bool> deledges(tpn u, tpn v) {
        bool b1 = deledge_by_vertex(u, v);
        bool b2 = deledge_by_vertex(v, u);
        return {b1, b2};
    }

    inline bool selfloop() const {
        for(int u=0;u<static_cast<int>(head.size())-1+1;++u) {
            for (ten e = head[u]; e != -1; e = edges[e].nxt) {
                if (edges[e].v == static_cast<tpn>(u)) {
                    return true;
                }
            }
        }
        return false;
    }

    inline std::vector<std::pair<tpn, ten>> getselfloop() const {
        std::vector<std::pair<tpn, ten>> loops;
        for(int u=0;u<static_cast<int>(head.size())-1+1;++u) {
            for (ten e = head[u]; e != -1; e = edges[e].nxt) {
                if (edges[e].v == static_cast<tpn>(u)) {
                    loops.emplace_back(static_cast<tpn>(u), e);
                }
            }
        }
        return loops;
    }

    inline bool removselfloop() {
        bool res = false;
        for(int u=0;u<static_cast<int>(head.size())-1+1;++u) {
            while (head[u] != -1 && edges[head[u]].v == static_cast<tpn>(u)) {
                head[u] = edges[head[u]].nxt;
            }
            ten prev = head[u];
            while (prev != -1 && edges[prev].nxt != -1) {
                if (edges[edges[prev].nxt].v == static_cast<tpn>(u)) {
                    edges[prev].nxt = edges[edges[prev].nxt].nxt;
                    res = true;
                } else {
                    prev = edges[prev].nxt;
                }
            }
        }
        return res;
    }

    inline bool dupedge() const {
        for(int u=0;u<static_cast<int>(head.size())-1+1;++u) {
            std::unordered_set<tpn> visited;
            for (ten e = head[u]; e != -1; e = edges[e].nxt) {
                if (visited.count(edges[e].v)) {
                    return true;
                }
                visited.insert(edges[e].v);
            }
        }
        return false;
    }

    inline ten first(tpn u) const {
        if (u >= static_cast<tpn>(head.size())) return -1;
        return head[u];
    }

    inline ten next(ten e) const {
        if (e < 0 || e >= m) return -1;
        return edges[e].nxt;
    }

    inline Edge gets(ten e) const {
        if (e < 0 || e >= m) return Edge();
        return edges[e];
    }

    bool operator==(const Graph& other) const {
        if (head.size() != other.head.size() || m != other.m) {
            return false;
        }
        auto edges1 = getSortedEdges();
        auto edges2 = other.getSortedEdges();
        if (edges1.size() != edges2.size()) return false;
        for(int i=0;i<static_cast<int>(edges1.size())-1+1;++i) {
            if (edges1[i] != edges2[i]) return false;
        }
        return true;
    }

    inline ten num() const { return m; }

    bool operator!=(const Graph& other) const { return !(*this == other); }

private:
    std::vector<ten> head;
    std::vector<Edge> edges;
    ten m;
    std::vector<tpw> node_weights;

    std::vector<std::tuple<tpn, tpn, tew>> getSortedEdges() const {
        std::vector<std::tuple<tpn, tpn, tew>> edgeList;
        for(int u=0;u<static_cast<int>(head.size())-1+1;++u) {
            for (ten e = head[u]; e != -1; e = edges[e].nxt) {
                edgeList.emplace_back(static_cast<tpn>(u), edges[e].v, edges[e].w);
            }
        }
        std::sort(edgeList.begin(), edgeList.end());
        return edgeList;
    }
};

using grf = Graph<int, int, int, int>;
教程

Graph 通用图模板类使用指南

注:下文中,以小写 gg 开头的变量的类型都是 Graph<..., ..., ..., ...>;以小写 ee 开头的变量类型都是 Edge。点和边均采用 0-based 计数!

一、模板实例化语法

核心语法

C++
Graph<点编号类型, 点权类型, 边编号类型, 边权类型> 图对象名;
using 别名 = Graph<类型1, 类型2, 类型3, 类型4>;
// 创建方法:别名 图对象名;    例:
Graph<int, int, int, int> g;

示例

C++
using grf = Graph<int, int, int, int>;
grf g;
using grf_adv = Graph<long long, double, size_t, long long>;
grf_adv g2;

二、图的初始化方法

方法语法功能说明语法示例
Graph()无参构造,初始化空图(顶点数 00、边数 00)grf g;(实例化空图)
Graph(tpn n, const tpw& default_weight = tpw{})初始化 nn 个顶点的图,所有顶点默认点权为default_weightgrf g(10, 1);(10个顶点,默认点权5)
Graph(const Graph& other)拷贝构造,创建与other完全相同的图grf g2(g1);(g2复制g1的所有内容)
Graph(Graph&& other) noexcept移动构造,高效转移other的资源grf g2(std::move(g1));(g1资源转移给g2,g1变为空)

三、赋值重载

语法功能说明语法示例
Graph& operator=(const Graph& other)拷贝赋值,将other的内容赋值给当前图g2 = g1;(g2复制g1的内容)
Graph& operator=(Graph&& other) noexcept移动赋值,高效转移other的资源g2 = std::move(g1);(g1资源转移给g2)

四、点权管理方法

方法语法功能说明语法示例
void set_node_weight(tpn u, const tpw& w)设置顶点 uu 的点权为 ww;uu 超出范围时自动扩容图g.set_node_weight(2, 10);(顶点2点权设为10);g.set_node_weight(15, 20);(顶点15越界,自动扩容至16个顶点,点权20)
tpw get_node_weight(tpn u) const获取顶点 uu 的点权;uu 越界时抛出std::out_of_range异常int w = g.get_node_weight(2);

五、边的操作方法

1. 新增边

方法语法功能说明语法示例
Edge addedge(tpn u, tpn v, tew w)添加边权为 ww 的有向边 u⟶vu\longrightarrow v,返回新增的 Edge 对象;uu / vv 越界时自动扩容g.addedge(0, 1, 2);(添加 0⟶10 \longrightarrow 1,边权 22)
std::pair<Edge, Edge> addedges(tpn u, tpn v, tew w)添加边权为 ww 的无向边 u⟷vu\longleftrightarrow v,返回两条边的 pairauto [e1, e2] = g.addedges(2, 3, 3);(添加 2⟷32\longleftrightarrow3,边权 33,接收两条边)

2. 删除边

方法语法功能说明语法示例
bool deledge_by_index(tpn u, ten e)按编号删除顶点 uu 的出边 ee;返回 true(删除成功)/ false(失败)bool flag = g.deledge_by_index(0, 0);(删除顶点 00 的出边 00)
bool deledge_by_vertex(tpn u, tpn v)删除顶点 uu 到 vv 的第一条有向边;返回 true(成功)/ false(失败)bool flag = g.deledge_by_vertex(0, 1);(删除 0⟶10\longrightarrow1 的边)
std::pair<bool, bool> deledges(tpn u, tpn v)删除无向边 u⟷vu\longleftrightarrow v;返回两个 bool 表示各自删除结果auto [f1, f2] = g.deledges(2, 3);(删除 2⟷32\longleftrightarrow3)

六、图的基础配置方法

方法语法功能说明语法示例
void resize(tpn n, const tpw& default_weight = tpw{})调整图的顶点数为 nn;新增顶点的点权为 default_weight(默认为 00)g.resize(12, 8);(顶点数扩至 1212,新增顶点默认点权 88)
tpn size() const返回当前图的顶点总数int cnt = g.size();
void clear()清空所有边,保留顶点和点权grf g(10);;g.clear();(清空所有边,顶点数仍为 1010)
void clear(tpn n, const tpw& default_weight = tpw{})重置为 nn 个顶点的空图,顶点默认点权为 default_weightg.clear(6, 4);(重置为 66 个顶点,默认点权 44)

七、图的合法性校验方法

方法语法功能说明语法示例
bool selfloop() const判断图中是否存在自环;返回 true / falsebool has = g.selfloop();
std::vector<std::pair<tpn, ten>> getselfloop() const返回所有自环的(顶点编号,边编号)对auto loops = g.getselfloop();
bool removselfloop()删除图中所有自环边,返回是否有自环g.removselfloop();
bool dupedge() const判断图中是否存在重边(同一顶点对的多条边);返回 true/falsebool has = g.dupedge();

八、邻接表遍历辅助方法

方法语法功能说明语法示例
ten first(tpn u) const获取顶点 uu 的第一条出边编号;uu 越界返回 −1-1int e = g.first(0);
ten next(ten e) const获取边 ee 的下一条边编号; ee 无效返回 −1-1int e1 = g.next(0);`
Edge gets(ten e) const获取编号为 ee 的边的完整信息(vv、ww、nxtnxt);ee 无效返回空 Edgegrf::Edge edge = g.gets(0);

九、运算符重载

语法功能说明语法示例
bool operator==(const Graph& other) const判断两个图是否完全相同(顶点数、边、点权一致);返回 true/falsebool eq = (g1 == g2);
bool operator!=(const Graph& other) const判断两个图是否不完全相同;返回!operator==的结果bool neq = (g1 != g2);

十、其他实用方法

方法语法功能说明语法示例
ten num() const返回当前图的总边数int cnt = g.num();
bool operator==(const Edge& other) const判断两条边是否相同(目标顶点+边权一致)bool eq = (e1 == e2);
bool operator!=(const Edge& other) const判断两条边是否不同bool neq = (e1 != e2);

十一、核心遍历语法(邻接表)

语法片段:

C++
tpn u = 目标顶点;
for (ten e = 图对象.first(u); e != -1; e = 图对象.next(e)) {
    Graph<...>::Edge edge = 图对象.gets(e);
    tpn v = edge.v;
    tew w = edge.w;
    // 自定义算法逻辑
}

功能说明:遍历顶点u的所有出边,获取目标顶点和边权。

完整示例:

C++
grf g(10);
g.addedge(0, 1, 2);
g.addedge(0, 2, 5);
int u = 0;
for (int e = g.first(u); e != -1; e = g.next(e)) {
    grf::Edge edge = g.gets(e);
    int v = edge.v;
    int w = edge.w;
    std::cout << u << "->" << v << ":" << w << std::endl; // 输出边信息
}

十二、关键语法说明

  1. 模板参数缩写含义:
    • tpn:顶点编号类型(Type of Node Number)
    • tpw:顶点权值类型(Type of Node Weight)
    • ten:边编号类型(Type of Edge Number)
    • tew:边权值类型(Type of Edge Weight)
  2. 返回值规则:
    • 布尔型返回值:true表示操作成功/条件满足,false反之;
    • 容器型返回值:如vector<pair<tpn, ten>>,空容器表示无对应结果;
    • 数值型返回值:-1通常表示“无/无效”(如无下一条边、顶点越界)。

留言:应该算是起了个好头吧……接力下一棒任务:std::vector<tew> dijkstra(tpn start)。