正文
增加 370 行删除 288 行
1234567891011123 行未改动1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883894 行未改动3943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394402 行未改动4434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355363 行未改动5405415425435445455465475485495505513 行未改动5555565575585595605615625635645655665675685695705715725735745755766 行未改动583584585586587588589590591592593594595596597598599600601602603604605606607608609# [关联内容](https://www.luogu.com.cn/problem/T718507)### 留言 1:这里是洛谷保存站,如果需要查看,请点击:“刷新内容”,否则可能看到错误信息。### 留言 2:为了你的代码长度不超限,[zszl](https://www.luogu.com.cn/user/1328402) 将会提供一个可读性为 0 的压缩版本。# 迭代与更新(upds):::::success[$\color{red} std.$ 2026/1/6 20:05 [zszl](https://www.luogu.com.cn/user/1328402)]:::info[代码]```c++#include <bits/stdc++.h>3 行未改动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>;```::::::info[压缩版本]```c++#include<bits/stdc++.h>#include<bits/extc++.h>#define int lltypedef 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>;```::::::info[教程]# `Graph` 通用图模板类使用指南 - 第一章 || 基础语法注:下文中,以小写 $g$ 开头的变量的类型都是 `Graph<..., ..., ..., ...>`;以小写 $e$ 开头的变量类型都是 `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()` | 无参构造,初始化空图(顶点数 $0$、边数 $0$) | `grf g;`(实例化空图) || `Graph(tpn n, const tpw& default_weight = tpw{})` | 初始化 $n$ 个顶点的图,所有顶点默认点权为`default_weight` | `grf 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变为空) |## 三、赋值重载4 行未改动## 四、点权管理方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `void set_node_weight(tpn u, const tpw& w)` | 设置顶点 $u$ 的点权为 $w$;$u$ 超出范围时自动扩容图 | `g.set_node_weight(2, 10);`(顶点2点权设为10);`g.set_node_weight(15, 20);`(顶点15越界,自动扩容至16个顶点,点权20) || `tpw get_node_weight(tpn u) const` | 获取顶点 $u$ 的点权;$u$ 越界时抛出`std::out_of_range`异常 | `int w = g.get_node_weight(2);` |## 五、边的操作方法### 1. 新增边| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `Edge addedge(tpn u, tpn v, tew w)` | 添加边权为 $w$ 的有向边 $u\longrightarrow v$,返回新增的 `Edge` 对象;$u$ / $v$ 越界时自动扩容 | `g.addedge(0, 1, 2);`(添加 $0 \longrightarrow 1$,边权 $2$) || `std::pair<Edge, Edge> addedges(tpn u, tpn v, tew w)` | 添加边权为 $w$ 的无向边 $u\longleftrightarrow v$,返回两条边的 `pair` | `auto [e1, e2] = g.addedges(2, 3, 3);`(添加 $2\longleftrightarrow3$,边权 $3$,接收两条边) |### 2. 删除边| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `bool deledge_by_index(tpn u, ten e)` | 按编号删除顶点 $u$ 的出边 $e$;返回 `true`(删除成功)/ `false`(失败) | `bool flag = g.deledge_by_index(0, 0);`(删除顶点 $0$ 的出边 $0$) || `bool deledge_by_vertex(tpn u, tpn v)` | 删除顶点 $u$ 到 $v$ 的第一条有向边;返回 `true`(成功)/ `false`(失败) | `bool flag = g.deledge_by_vertex(0, 1);`(删除 $0\longrightarrow1$ 的边) || `std::pair<bool, bool> deledges(tpn u, tpn v)` | 删除无向边 $u\longleftrightarrow v$;返回两个 `bool` 表示各自删除结果 | `auto [f1, f2] = g.deledges(2, 3);`(删除 $2\longleftrightarrow3$) |## 六、图的基础配置方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `void resize(tpn n, const tpw& default_weight = tpw{})` | 调整图的顶点数为 $n$;新增顶点的点权为 `default_weight`(默认为 $0$) | `g.resize(12, 8);`(顶点数扩至 $12$,新增顶点默认点权 $8$) || `tpn size() const` | 返回当前图的顶点总数 | `int cnt = g.size();` || `void clear()` | 清空所有边,**保留顶点和点权** | `grf g(10);`;`g.clear();`(清空所有边,顶点数仍为 $10$) || `void clear(tpn n, const tpw& default_weight = tpw{})` | 重置为 $n$ 个顶点的空图,顶点默认点权为 `default_weight` | `g.clear(6, 4);`(重置为 $6$ 个顶点,默认点权 $4$) |## 七、图的合法性校验方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `bool selfloop() const` | 判断图中是否存在自环;返回 `true` / `false` | `bool has = g.selfloop();` || `std::vector<std::pair<tpn, ten>> getselfloop() const` | 返回所有自环的(顶点编号,边编号)对 | `auto loops = g.getselfloop();` || `bool removselfloop()` | 删除图中所有自环边,返回是否有自环 | `g.removselfloop();` || `bool dupedge() const` | 判断图中是否存在重边(同一顶点对的多条边);返回 `true`/`false` | `bool has = g.dupedge();` |## 八、邻接表遍历辅助方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `ten first(tpn u) const` | 获取顶点 $u$ 的第一条出边编号;$u$ 越界返回 $-1$ | `int e = g.first(0);` || `ten next(ten e) const` | 获取边 $e$ 的下一条边编号; $e$ 无效返回 $-1$ | `int e1 = g.next(0);` || `Edge gets(ten e) const` | 获取编号为 $e$ 的边的完整信息($v$、$w$、$nxt$);$e$ 无效返回空 `Edge` | `grf::Edge edge = g.gets(0);` |## 九、运算符重载| 语法 | 功能说明 | 语法示例 ||-|-|-|2 行未改动## 十、其他实用方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `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)`。::::::::::success[$\color{red} dijkstra.$ 2026/1/7 21:01 [zszl](https://www.luogu.com.cn/user/1328402)]:::info[代码]```c++std::vector<tew> dijkstra(tpn start) {std::vector<std::pair<tew, bool>> state(head.size(), {0, false});if (start < 0 || start >= static_cast<tpn>(head.size())) {std::cerr << "Start vertex out of range!" << std::endl;state.assign(head.size(), {0, false});} else {bool has_negative = false;for (ten e = 0; e < m; ++e) {if (edges[e].w < 0) { has_negative = true; break; }}if (!has_negative) {Graph g2 = *this;g2.removselfloop();std::vector<std::unordered_map<tpn, tew>> min_edge(g2.size());for (tpn u = 0; u < g2.size(); ++u) {for (ten e = g2.first(u); e != -1; e = g2.next(e)) {auto edge = g2.gets(e);if (min_edge[u].find(edge.v) == min_edge[u].end() || edge.w < min_edge[u][edge.v]) {min_edge[u][edge.v] = edge.w;}}}g2.clear();for (tpn u = 0; u < g2.size(); ++u) {for (const auto& [v, w] : min_edge[u]) { g2.addedge(u, v, w); }}state.assign(g2.size(), {0, false});state[start].first = 0;state[start].second = true;bool use_pbds_heap = (m > 1e6);using PII = std::pair<tew, tpn>;if (use_pbds_heap) {__gnu_pbds::priority_queue<PII, std::greater<PII>, __gnu_pbds::pairing_heap_tag> pq;std::vector<typename decltype(pq)::point_iterator> iters(g2.size(), nullptr);3 行未改动auto [cur_dist, u] = pq.top();pq.pop();if (cur_dist > state[u].first && state[u].second) continue;for (ten e = g2.first(u); e != -1; e = g2.next(e)) {auto edge = g2.gets(e);tpn v = edge.v;tew new_dist = cur_dist + edge.w;if (!state[v].second || new_dist < state[v].first) {state[v].first = new_dist;state[v].second = true;if (iters[v] != nullptr) {3 行未改动}}}}}else {std::priority_queue<PII, std::vector<PII>, std::greater<PII>> pq;pq.emplace(0, start);while (!pq.empty()) {auto [cur_dist, u] = pq.top();pq.pop();if (cur_dist > state[u].first && state[u].second) continue;for (ten e = g2.first(u); e != -1; e = g2.next(e)) {auto edge = g2.gets(e);tpn v = edge.v;tew new_dist = cur_dist + edge.w;if (!state[v].second || new_dist < state[v].first) {state[v].first = new_dist;state[v].second = true;pq.emplace(new_dist, v);6 行未改动state.assign(head.size(), {0, false});}}std::vector<tew> dist(head.size(), static_cast<tew>(-1));for (tpn i = 0; i < state.size(); ++i) {if (state[i].second) {dist[i] = state[i].first;}}return dist;}```::::::info[压缩版本]```c++inline std::vector<tew> dijkstra(tpn start){std::vector<std::pair<tew,bool>> state(head.size(),{0,false});if(start<0||start>=static_cast<tpn>(head.size())){std::cerr<<"Start vertex out of range!"<<std::endl;state.assign(head.size(),{0,false});}else{bool has_negative=false;for(ten e=0;e<m;++e){if(edges[e].w<0){has_negative=true;break;}}if(!has_negative){Graph g2=*this;g2.removselfloop();std::vector<std::unordered_map<tpn,tew>> min_edge(g2.size());for(tpn u=0;u<g2.size();++u){for(ten e=g2.first(u);e!=-1;e=g2.next(e)){auto edge=g2.gets(e);if(min_edge[u].find(edge.v)==min_edge[u].end()||edge.w<min_edge[u][edge.v]){min_edge[u][edge.v]=edge.w;}}}g2.clear();for(tpn u=0;u<g2.size();++u){for(const auto&[v,w]:min_edge[u]){g2.addedge(u,v,w);}}state.assign(g2.size(),{0,false});state[start].first=0;state[start].second=true;bool use_pbds_heap=(m>1e6);using PII=std::pair<tew,tpn>;if(use_pbds_heap){__gnu_pbds::priority_queue<PII,std::greater<PII>,__gnu_pbds::pairing_heap_tag> pq;std::vector<typename decltype(pq)::point_iterator> iters(g2.size(),nullptr);iters[start]=pq.push(PII(0,start));while(!pq.empty()){auto[cur_dist,u]=pq.top();pq.pop();if(cur_dist>state[u].first&&state[u].second)continue;for(ten e=g2.first(u);e!=-1;e=g2.next(e)){auto edge=g2.gets(e);tpn v=edge.v;tew new_dist=cur_dist+edge.w;if(!state[v].second||new_dist<state[v].first){state[v].first=new_dist;state[v].second=true;if(iters[v]!=nullptr){pq.modify(iters[v],PII(new_dist,v));}else{iters[v]=pq.push(PII(new_dist,v));}}}}}else{std::priority_queue<PII,std::vector<PII>,std::greater<PII>> pq;pq.emplace(0,start);while(!pq.empty()){auto[cur_dist,u]=pq.top();pq.pop();if(cur_dist>state[u].first&&state[u].second)continue;for(ten e=g2.first(u);e!=-1;e=g2.next(e)){auto edge=g2.gets(e);tpn v=edge.v;tew new_dist=cur_dist+edge.w;if(!state[v].second||new_dist<state[v].first){state[v].first=new_dist;state[v].second=true;pq.emplace(new_dist,v);}}}} }else{std::cerr<<"Negative edges not supported!"<<std::endl;state.assign(head.size(),{0,false});}}std::vector<tew> dist(head.size(),static_cast<tew>(-1));for(tpn i=0;i<state.size();++i){if(state[i].second){dist[i]=state[i].first;}}return dist;}```::::::info[教程]# `Graph` 通用图模板类使用指南 - 第二章 || 最短路| | 定义 | 功能 | 实现方法 | 调用例子 ||:-:|-|-|-|-|| **dijkstra** | `std::vector<tew> dijkstra(tpn start)` | 以 `start` 作为起点的最短路,返回值满足:如果存在则为最短长度,不存在则为 $-1$,存在负边权自动向 `stderr` 发送错误 | 自动判断剪枝小根堆或配对堆 | `auto dis = g.dijkstra(0);` |::::::::123453 行未改动91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313324 行未改动3373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823832 行未改动3863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744753 行未改动4794804814824834844854864874884894903 行未改动4944954964974984995005015025035045055065075085095105115125135146 行未改动521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691::::::success[基础模板]:::::success[$\color{red} std.$ 2026/1/6 20:05 [zszl](https://www.luogu.com.cn/user/1328402)]:::info[代码]```c++#include <bits/stdc++.h>3 行未改动typedef long long ll;typedef long double db;using pii = std::pair<int, int>;typedef unsigned long long ull;template<typename tp=int, typename te=int>class Graph {public:struct Edge {int v;te w;int nxt;Edge() noexcept : v(0), w(0), nxt(-1) {}Edge(int _v, te _w, int _nxt) noexcept : v(_v), w(_w), nxt(_nxt) {}bool operator==(const Edge& other) const noexcept {return v == other.v && w == other.w;}bool operator!=(const Edge& other) const noexcept {return !(*this == other);}};Graph() noexcept : m(0) {}Graph(int n, const tp& default_weight = tp{}) noexcept : head(n, -1), m(0), node_weights(n, default_weight) {}Graph(const Graph& other) = default;Graph(Graph&& other) noexcept = default;Graph& operator=(const Graph& other) = default;Graph& operator=(Graph&& other) noexcept = default;inline void resize(int n, const tp& default_weight = tp{}) noexcept {const int old_size = head.size();if (n > old_size) {head.resize(n, -1);node_weights.resize(n, default_weight);} else if (n < old_size) {head.resize(n);node_weights.resize(n);}}inline int size() const noexcept {return head.size();}inline void clear() noexcept {std::fill(head.begin(), head.end(), -1);edges.clear();m = 0;}inline void clear(int n, const tp& default_weight = tp{}) noexcept {head.assign(n, -1);node_weights.assign(n, default_weight);edges.clear();m = 0;}inline void set_node_weight(int u, const tp& weight) noexcept {if (u > (int)node_weights.size())-1 resize(u + 1);node_weights[u] = weight;}inline tp get_node_weight(int u) const {if (u > (int)node_weights.size()-1)throw std::out_of_range("Node index out of bounds");return node_weights[u];}inline Edge addedge(int u, int v, te w) noexcept {if (u > (int)head.size()-1 || v > (int)head.size()-1) {int new_size = std::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(int u, int v, te w) noexcept {if (u > (int)head.size()-1 || v > (int)head.size()-1) {int new_size = std::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(int u, int e) noexcept {if (u > (int)head.size()-1 || !~head[u]) return false;if (head[u] == e) {head[u] = edges[e].nxt;return true;}int prev = head[u];while (~prev && edges[prev].nxt != e) prev = edges[prev].nxt;if (!~prev) return false;edges[prev].nxt = edges[e].nxt;return true;}inline bool deledge_by_vertex(int u, int v) noexcept {if (u > (int)head.size()-1 || !~head[u]) return false;if (edges[head[u]].v == v) {int e = head[u];head[u] = edges[e].nxt;return true;}int prev = head[u];while (~prev) {if (~edges[prev].nxt && edges[edges[prev].nxt].v == v) {int e = edges[prev].nxt;edges[prev].nxt = edges[e].nxt;return true;}prev = edges[prev].nxt;}return false;}inline std::pair<bool, bool> deledges(int u, int v) noexcept {bool b1 = deledge_by_vertex(u, v);bool b2 = deledge_by_vertex(v, u);return {b1, b2};}inline int first(int u) const noexcept {if (u > (int)head.size()-1) return -1;return head[u];}inline int next(int e) const noexcept {if (e < 0 || e > m-1) return -1;return edges[e].nxt;}inline Edge gets(int e) const noexcept {if (e < 0 || e > m-1) return Edge();return edges[e];}bool operator==(const Graph& other) const noexcept {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 < (int)edges1.size(); ++i) {if (edges1[i] != edges2[i]) return false;}return true;}inline int num() const noexcept { return m; }bool operator!=(const Graph& other) const noexcept { return !(*this == other); }private:std::vector<int> head;std::vector<Edge> edge;int m;std::vector<tp> node_weights;std::vector<std::tuple<int, int, te>> getSortedEdges() const noexcept {std::vector<std::tuple<int, int, te>> edgeList;for (int i = 0; i < (int)head.size(); ++i) {for (int e = head[i]; ~e; e = edges[e].nxt) {edgeList.emplace_back(i, edges[e].v, edges[e].w);}}std::sort(edgeList.begin(), edgeList.end());return edgeList;}};using grf = Graph<int, int>;```::::::info[压缩版本]```c++#include <bits/stdc++.h>#include <bits/extc++.h>#define int lltypedef long long ll;typedef long double db;using pii=std::pair<int,int>;typedef unsigned long long ull;template<typename tp=int,typename te=int>class Graph {public:struct Edge {int v; te w; int nxt;Edge()noexcept:v(0),w(0),nxt(-1){}Edge(int _v,te _w,int _nxt)noexcept:v(_v),w(_w),nxt(_nxt){}bool operator==(const Edge&other)const noexcept{return v==other.v&&w==other.w;}bool operator!=(const Edge&other)const noexcept{return!(*this==other);}};Graph()noexcept:m(0){}Graph(int n,const tp&default_weight=tp{})noexcept:head(n,-1),m(0),node_weights(n,default_weight){}Graph(const Graph&other)=default;Graph(Graph&&other)noexcept=default;Graph&operator=(const Graph&other)=default;Graph&operator=(Graph&&other)noexcept=default;inline void resize(int n,const tp&default_weight=tp{})noexcept{const int old_size=head.size();if(n>old_size){head.resize(n,-1);node_weights.resize(n,default_weight);}else if(n<old_size){head.resize(n);node_weights.resize(n);}}inline int size()const noexcept{return head.size();}inline void clear()noexcept{std::fill(head.begin(),head.end(),-1);edges.clear();m=0;}inline void clear(int n,const tp&default_weight=tp{})noexcept{head.assign(n,-1);node_weights.assign(n,default_weight);edges.clear();m=0;}inline void set_node_weight(int u,const tp&weight)noexcept{if(u>(int)node_weights.size()-1)resize(u+1);node_weights[u]=weight;}inline tp get_node_weight(int u)const{if(u>(int)node_weights.size()-1)throw std::out_of_range("Node index out of bounds");return node_weights[u];}inline Edge addedge(int u,int v,te w)noexcept{if(u>(int)head.size()-1||v>(int)head.size()-1){int new_size=std::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(int u,int v,te w)noexcept{if(u>(int)head.size()-1||v>(int)head.size()-1){int new_size=std::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(int u,int e)noexcept{if(u>(int)head.size()-1||!~head[u])return false;if(head[u]==e){head[u]=edges[e].nxt;return true;}int prev=head[u];while(~prev&&edges[prev].nxt!=e)prev=edges[prev].nxt;if(!~prev)return false;edges[prev].nxt=edges[e].nxt;return true;}inline bool deledge_by_vertex(int u,int v)noexcept{if(u>(int)head.size()-1||!~head[u])return false;if(edges[head[u]].v==v){int e=head[u];head[u]=edges[e].nxt;return true;}int prev=head[u];while(~prev){if(~edges[prev].nxt&&edges[edges[prev].nxt].v==v){int e=edges[prev].nxt;edges[prev].nxt=edges[e].nxt;return true;}prev=edges[prev].nxt;}return false;}inline std::pair<bool,bool> deledges(int u,int v)noexcept{bool b1=deledge_by_vertex(u,v);bool b2=deledge_by_vertex(v,u);return{b1,b2};}inline int first(int u)const noexcept{if(u>(int)head.size()-1)return-1;return head[u];}inline int next(int e)const noexcept{if(e<0||e>m-1)return-1;return edges[e].nxt;}inline Edge gets(int e)const noexcept{if(e<0||e>m-1)return Edge();return edges[e];}bool operator==(const Graph&other)const noexcept{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<(int)edges1.size();++i){if(edges1[i]!=edges2[i])return false;}return true;}inline int num()const noexcept{return m;}bool operator!=(const Graph&other)const noexcept{return!(*this==other);}private:std::vector<int> head;std::vector<Edge> edges;int m;std::vector<tp> node_weights;std::vector<std::tuple<int,int,te>> getSortedEdges()const noexcept{std::vector<std::tuple<int,int,te>> edgeList;for(int i=0;i<(int)head.size();++i){for(int e=head[i];~e;e=edges[e].nxt){edgeList.emplace_back(i,edges[e].v,edges[e].w);}}std::sort(edgeList.begin(),edgeList.end());return edgeList;}};using grf=Graph<int,int>;```:::::::::::::success[$\color{red} slf \ \& \ dpe.$ 2026/1/6 20:20 [zszl](https://www.luogu.com.cn/user/1328402)]前置:$\color{red} std$。:::info[代码]```c++inline bool selfloop() const noexcept {for (int i = 0; i < (int)head.size(); ++i) {for (int e = head[i]; ~e; e = edges[e].nxt) {if (edges[e].v == i) return true;}}return false;}inline std::vector<std::pair<int, int>> getselfloop() const noexcept {std::vector<std::pair<int, int>> loops;for (int i = 0; i < (int)head.size(); ++i) {for (int e = head[i]; ~e; e = edges[e].nxt) {if (edges[e].v == i) loops.emplace_back(i, e);}}return loops;}inline bool removselfloop() noexcept {bool res = false;for (int i = 0; i < (int)head.size(); ++i) {while (~head[i] && edges[head[i]].v == i) head[i] = edges[head[i]].nxt;int prev = head[i];while (~prev && ~edges[prev].nxt) {if (edges[edges[prev].nxt].v == i) {edges[prev].nxt = edges[edges[prev].nxt].nxt;res = true;} else prev = edges[prev].nxt;}}return res;}inline bool dupedge() const noexcept {for (int i = 0; i < (int)head.size(); ++i) {std::vector<int> visited;for (int e = head[i]; ~e; e = edges[e].nxt) {int v = edges[e].v;for (int x : visited) if (x == v) return true;visited.push_back(v);}}return false;}```::::::info[压缩版本]```c++inline bool selfloop()const noexcept{for(int i=0;i<(int)head.size();++i){for(int e=head[i];~e;e=edges[e].nxt){if(edges[e].v==i)return true;}}return false;}inline std::vector<std::pair<int,int>> getselfloop()const noexcept{std::vector<std::pair<int,int>> loops;for(int i=0;i<(int)head.size();++i){for(int e=head[i];~e;e=edges[e].nxt){if(edges[e].v==i)loops.emplace_back(i,e);}}return loops;}inline bool removselfloop()noexcept{bool res=false;for(int i=0;i<(int)head.size();++i){while(~head[i]&&edges[head[i]].v==i)head[i]=edges[head[i]].nxt;int prev=head[i];while(~prev&&~edges[prev].nxt){if(edges[edges[prev].nxt].v==i){edges[prev].nxt=edges[edges[prev].nxt].nxt;res=true;}else prev=edges[prev].nxt;}}return res;}inline bool dupedge()const noexcept{for(int i=0;i<(int)head.size();++i){std::vector<int> visited;for(int e=head[i];~e;e=edges[e].nxt){int v=edges[e].v;for(int x:visited)if(x==v)return true;visited.push_back(v);}}return false;}```:::::::::::info[教程]# `Graph` 通用图模板类使用指南 - 第一章 || 基础语法注:下文中,以小写 $g$ 开头的变量的类型都是 `Graph<..., ...>`;以小写 $e$ 开头的变量类型都是 `Edge`。**点和边均采用 0-based 计数!**## 一、模板实例化语法### 核心语法```c++Graph<点权类型, 边权类型> 图对象名;using 别名 = Graph<类型1, 类型2>;Graph<int, int> g;```### 示例```c++using grf = Graph<int, int>;grf g;using grf_adv = Graph<long long, double>;grf_adv g2;```## 二、图的初始化方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `Graph()` | 无参构造,初始化空图(顶点数 $0$、边数 $0$) | `grf g;`(实例化空图) || `Graph(int n, const tp& default_weight = tp{})` | 初始化 $n$ 个顶点的图,所有顶点默认点权为`default_weight` | `grf 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变为空) |## 三、赋值重载4 行未改动## 四、点权管理方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `void set_node_weight(int u, const tp& w)` | 设置顶点 $u$ 的点权为 $w$;$u$ 超出范围时自动扩容图 | `g.set_node_weight(2, 10);`(顶点2点权设为10);`g.set_node_weight(15, 20);`(顶点15越界,自动扩容至16个顶点,点权20) || `tp get_node_weight(int u) const` | 获取顶点 $u$ 的点权;$u$ 越界时抛出`std::out_of_range`异常 | `int w = g.get_node_weight(2);` |## 五、边的操作方法### 1. 新增边| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `Edge addedge(int u, int v, te w)` | 添加边权为 $w$ 的有向边 $u\longrightarrow v$,返回新增的 `Edge` 对象;$u$ / $v$ 越界时自动扩容 | `g.addedge(0, 1, 2);`(添加 $0 \longrightarrow 1$,边权 $2$) || `std::pair<Edge, Edge> addedges(int u, int v, te w)` | 添加边权为 $w$ 的无向边 $u\longleftrightarrow v$,返回两条边的 `pair` | `auto [e1, e2] = g.addedges(2, 3, 3);`(添加 $2\longleftrightarrow3$,边权 $3$,接收两条边) |### 2. 删除边| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `bool deledge_by_index(int u, int e)` | 按编号删除顶点 $u$ 的出边 $e$;返回 `true`(删除成功)/ `false`(失败) | `bool flag = g.deledge_by_index(0, 0);`(删除顶点 $0$ 的出边 $0$) || `bool deledge_by_vertex(int u, int v)` | 删除顶点 $u$ 到 $v$ 的第一条有向边;返回 `true`(成功)/ `false`(失败) | `bool flag = g.deledge_by_vertex(0, 1);`(删除 $0\longrightarrow1$ 的边) || `std::pair<bool, bool> deledges(int u, int v)` | 删除无向边 $u\longleftrightarrow v$;返回两个 `bool` 表示各自删除结果 | `auto [f1, f2] = g.deledges(2, 3);`(删除 $2\longleftrightarrow3$) |## 六、图的基础配置方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `void resize(int n, const tp& default_weight = tp{})` | 调整图的顶点数为 $n$;新增顶点的点权为 `default_weight`(默认为 $0$) | `g.resize(12, 8);`(顶点数扩至 $12$,新增顶点默认点权 $8$) || `int size() const` | 返回当前图的顶点总数 | `int cnt = g.size();` || `void clear()` | 清空所有边,**保留顶点和点权** | `grf g(10);`;`g.clear();`(清空所有边,顶点数仍为 $10$) || `void clear(int n, const tp& default_weight = tp{})` | 重置为 $n$ 个顶点的空图,顶点默认点权为 `default_weight` | `g.clear(6, 4);`(重置为 $6$ 个顶点,默认点权 $4$) |## 七、图的合法性校验方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `bool selfloop() const` | 判断图中是否存在自环;返回 `true` / `false` | `bool has = g.selfloop();` || `std::vector<std::pair<int, int>> getselfloop() const` | 返回所有自环的(顶点编号,边编号)对 | `auto loops = g.getselfloop();` || `bool removselfloop()` | 删除图中所有自环边,返回是否有自环 | `g.removselfloop();` || `bool dupedge() const` | 判断图中是否存在重边(同一顶点对的多条边);返回 `true`/`false` | `bool has = g.dupedge();` |## 八、邻接表遍历辅助方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `int first(int u) const` | 获取顶点 $u$ 的第一条出边编号;$u$ 越界返回 $-1$ | `int e = g.first(0);` || `int next(int e) const` | 获取边 $e$ 的下一条边编号; $e$ 无效返回 $-1$ | `int e1 = g.next(0);` || `Edge gets(int e) const` | 获取编号为 $e$ 的边的完整信息($v$、$w$、$nxt$);$e$ 无效返回空 `Edge` | `grf::Edge edge = g.gets(0);` |## 九、运算符重载| 语法 | 功能说明 | 语法示例 ||-|-|-|2 行未改动## 十、其他实用方法| 方法语法 | 功能说明 | 语法示例 ||-|-|-|| `int 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++int u = 目标顶点;for (int e = 图对象.first(u); ~e; e = 图对象.next(e)) {Graph<...>::Edge edge = 图对象.gets(e);int v = edge.v;te 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; 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. **模板参数缩写含义**:- `tp`:顶点权值类型(Type of Node weight)- `te`:边权值类型(Type of Edge weight)2. **返回值规则**:- 布尔型返回值:`true`表示操作成功/条件满足,`false`反之;- 容器型返回值:如`vector<pair<int, int>>`,空容器表示无对应结果;- 数值型返回值:`-1`通常表示“无/无效”(如无下一条边、顶点越界)。:::::::::::::::success[最短路]:::::success[$\color{red} dijkstra.$ 2026/1/7 21:01 [zszl](https://www.luogu.com.cn/user/1328402)]前置:$\color{red} std, slf$。:::info[代码]```c++std::vector<std::pair<te, bool>> dijkstra(int start) {std::vector<std::pair<te, bool>> state(head.size(), {0, false});if (start < 0 || start > (int)head.size()-1) {std::cerr << "Start vertex out of range!" << std::endl;state.assign(head.size(), {0, false});} else {bool has_negative = false;for (int e = 0; e < m; ++e) {if (edges[e].w < 0) { has_negative = true; break; }}if (!has_negative) {Graph g2 = *this;g2.removselfloop();std::vector<std::unordered_map<int, te>> min_edge(g2.size());for (int u = 0; u < g2.size(); ++u) {for (int e = g2.first(u); ~e; e = g2.next(e)) {auto edge = g2.gets(e);if (min_edge[u].find(edge.v) == min_edge[u].end() || edge.w < min_edge[u][edge.v]) {min_edge[u][edge.v] = edge.w;}}}g2.clear();for (int u = 0; u < g2.size(); ++u) {for (const auto& [v, w] : min_edge[u]) { g2.addedge(u, v, w); }}state.assign(g2.size(), {0, false});state[start].first = 0;state[start].second = true;bool use_pbds_heap = (m > 1e6);using PII = std::pair<te, int>;if (use_pbds_heap) {__gnu_pbds::priority_queue<PII, std::greater<PII>, __gnu_pbds::pairing_heap_tag> pq;std::vector<typename decltype(pq)::point_iterator> iters(g2.size(), nullptr);3 行未改动auto [cur_dist, u] = pq.top();pq.pop();if (cur_dist > state[u].first && state[u].second) continue;for (int e = g2.first(u); ~e; e = g2.next(e)) {auto edge = g2.gets(e);int v = edge.v;te new_dist = cur_dist + edge.w;if (!state[v].second || new_dist < state[v].first) {state[v].first = new_dist;state[v].second = true;if (iters[v] != nullptr) {3 行未改动}}}}} else {std::priority_queue<PII, std::vector<PII>, std::greater<PII>> pq;pq.emplace(0, start);while (!pq.empty()) {auto [cur_dist, u] = pq.top();pq.pop();if (cur_dist > state[u].first && state[u].second) continue;for (int e = g2.first(u); ~e; e = g2.next(e)) {auto edge = g2.gets(e);int v = edge.v;te new_dist = cur_dist + edge.w;if (!state[v].second || new_dist < state[v].first) {state[v].first = new_dist;state[v].second = true;pq.emplace(new_dist, v);6 行未改动state.assign(head.size(), {0, false});}}return state;}```::::::info[压缩版本]```c++std::vector<std::pair<te,bool>>dijkstra(int start){std::vector<std::pair<te,bool>>state(head.size(),{0,false});if(start<0||start>(int)head.size()-1){std::cerr<<"Start vertex out of range!"<<std::endl;state.assign(head.size(),{0,false});}else{bool has_negative=false;for(int e=0;e<m;++e){if(edges[e].w<0){has_negative=true;break;}}if(!has_negative){Graph g2=*this;g2.removselfloop();std::vector<std::unordered_map<int,te>>min_edge(g2.size());for(int u=0;u<g2.size();++u){for(int e=g2.first(u);~e;e=g2.next(e)){auto edge=g2.gets(e);if(min_edge[u].find(edge.v)==min_edge[u].end()||edge.w<min_edge[u][edge.v]){min_edge[u][edge.v]=edge.w;}}}g2.clear();for(int u=0;u<g2.size();++u){for(const auto&[v,w]:min_edge[u]){g2.addedge(u,v,w);}}state.assign(g2.size(),{0,false});state[start].first=0;state[start].second=true;bool use_pbds_heap=(m>1e6);using PII=std::pair<te,int>;if(use_pbds_heap){__gnu_pbds::priority_queue<PII,std::greater<PII>,__gnu_pbds::pairing_heap_tag>pq;std::vector<typename decltype(pq)::point_iterator>iters(g2.size(),nullptr);iters[start]=pq.push(PII(0,start));while(!pq.empty()){auto[cur_dist,u]=pq.top();pq.pop();if(cur_dist>state[u].first&&state[u].second)continue;for(int e=g2.first(u);~e;e=g2.next(e)){auto edge=g2.gets(e);int v=edge.v;te new_dist=cur_dist+edge.w;if(!state[v].second||new_dist<state[v].first){state[v].first=new_dist;state[v].second=true;if(iters[v]!=nullptr){pq.modify(iters[v],PII(new_dist,v));}else{iters[v]=pq.push(PII(new_dist,v));}}}}}else{std::priority_queue<PII,std::vector<PII>,std::greater<PII>>pq;pq.emplace(0,start);while(!pq.empty()){auto[cur_dist,u]=pq.top();pq.pop();if(cur_dist>state[u].first&&state[u].second)continue;for(int e=g2.first(u);~e;e=g2.next(e)){auto edge=g2.gets(e);int v=edge.v;te new_dist=cur_dist+edge.w;if(!state[v].second||new_dist<state[v].first){state[v].first=new_dist;state[v].second=true;pq.emplace(new_dist,v);}}}}}else{std::cerr<<"Negative edges not supported!"<<std::endl;state.assign(head.size(),{0,false});}}return state;}```:::::::::::::success[$\color{red} Bellman-Ford.$ 2026/1/8 19:35 [zszl](https://www.luogu.com.cn/user/1328402)]前置:$\color{red}std$。:::info[代码]```c++std::pair<std::vector<std::pair<te, bool>>, bool> bellman_ford(int start, int count = -1) {std::vector<std::pair<te, bool>> state(size(), {0, false});if (start > -1 && start < size()) {state[start].first = 0;state[start].second = true;}int node_num = head.size();int relax_times = std::min((count == -1) ? (node_num - 1) : count, node_num - 1);bool has_negative_cycle = false;for (int round = 0; round < relax_times; ++round) {bool updated = false;std::vector<std::pair<te, bool>> prev_state = state;for (int u = 0; u < node_num; ++u) {if (!prev_state[u].second) {continue;}for (int e = head[u]; ~e; e = edges[e].nxt) {Edge edge = edges[e];te new_dist = prev_state[u].first + edge.w;if (!state[edge.v].second || new_dist < state[edge.v].first) {state[edge.v].first = new_dist;state[edge.v].second = true;updated = true;}}}if (!updated) {break;}}std::vector<std::pair<te, bool>> final_state = state;for (int u = 0; u < node_num; ++u) {if (!final_state[u].second) {continue;}for (int e = head[u]; ~e; e = edges[e].nxt) {Edge edge = edges[e];te new_dist = final_state[u].first + edge.w;if (final_state[edge.v].second && new_dist < final_state[edge.v].first) {has_negative_cycle = true;break;}}if (has_negative_cycle) {break;}}return {state, has_negative_cycle};}```::::::info[压缩版本]```c++std::pair<std::vector<std::pair<te,bool>>,bool> bellman_ford(int start, int count=-1){std::vector<std::pair<te,bool>> state(size(),{0,false});if(start>=0&&start<size())state[start]={0,true};int node_num=head.size();int relax_times=std::min((count==-1)?(node_num-1):count,node_num-1);bool has_negative_cycle=false;for(int round=0;round<relax_times;++round){bool updated=false;std::vector<std::pair<te,bool>> prev_state=state;for(int u=0;u<node_num;++u){if(!prev_state[u].second)continue;for(int e=head[u];~e;e=edges[e].nxt){Edge edge=edges[e];te new_dist=prev_state[u].first+edge.w;if(!state[edge.v].second||new_dist<state[edge.v].first){state[edge.v]={new_dist,true};updated=true;}}}if(!updated)break;}std::vector<std::pair<te,bool>> final_state=state;for(int u=0;u<node_num;++u){if(!final_state[u].second)continue;for(int e=head[u];~e;e=edges[e].nxt){Edge edge=edges[e];te new_dist=final_state[u].first+edge.w;if(final_state[edge.v].second&&new_dist<final_state[edge.v].first){has_negative_cycle=true;break;}}if(has_negative_cycle)break;}return{state,has_negative_cycle};}```:::::::::::::success[$\color{red} SPFA.$ 2026/1/8 20:09 [zszl](https://www.luogu.com.cn/user/1328402)]前置:$\color{red}std$。:::info[代码]```c++std::pair<std::vector<te>, bool> spfa(int start) {int n = size();std::vector<te> dist(n, -1);std::vector<bool> in_queue(n, false);std::vector<int> in_cnt(n, 0);std::queue<int> q;dist[start] = 0;in_queue[start] = true;++in_cnt[start];q.emplace(start);bool has_neg_cycle = false;while (!q.empty() && !has_neg_cycle) {int u = q.front();q.pop();in_queue[u] = false;for (int e = head[u]; ~e; e = edges[e].nxt) {Edge edge = edges[e];int v = edge.v;te w = edge.w;if (dist[v] == -1 || dist[u] + w < dist[v]) {dist[v] = dist[u] + w;if (!in_queue[v]) {in_cnt[v]++;if (in_cnt[v] > n) {has_neg_cycle = true;break;}q.emplace(v);in_queue[v] = true;}}}}return {dist, has_neg_cycle};}```::::::info[压缩版本]```c++std::pair<std::vector<te>,bool> spfa(int start){int n=size();std::vector<te> dist(n,-1);std::vector<bool> in_q(n,false);std::vector<int> in_cnt(n,0);std::queue<int> q;dist[start]=0;in_q[start]=true;in_cnt[start]++;q.emplace(start);bool hnc=false;while(!q.empty()&&!hnc){int u=q.front();q.pop();in_q[u]=false;for(int e=head[u];~e;e=edges[e].nxt){Edge ed=edges[e];int v=ed.v;te w=ed.w;if(dist[v]==-1||dist[u]+w<dist[v]){dist[v]=dist[u]+w;if(!in_q[v]){in_cnt[v]++;if(in_cnt[v]>n){hnc=true;break;}q.emplace(v);in_q[v]=true;}}}}return{dist,hnc};}```:::::::::::info[教程]# `Graph` 通用图模板类使用指南 - 第二章 || 最短路**注:下文中称 `distance` 为 `std::pair<te, bool>` 的缩写,表示“距离”,第一个参数是实际的距离,第二个参数是是否能够到达。**## 一、dijkstra定义:`std::vector<distance> dijkstra(int start)`。功能:以 `start` 作为起点的最短路,返回值满足:如果存在则为最短长度,不存在则为 $-1$,存在负边权自动向 `stderr` 发送错误。实现逻辑:自动判断剪枝小根堆或配对堆。例子:`auto dis = g.dijkstra(0);`。## 二、Bellman-Ford定义:`std::pair<std::vector<distance>,bool> bellman_ford(int start, int count=-1)`。功能:以 `start` 作为起点的最短路,返回值 `first` 满足:如果存在则为最短长度,不存在则为 $-1$。`count` 表示松弛次数,默认为 $-1$ 表示松弛 $n-1$ 次。如果 `count > n-1`,则令 `count = n-1`。返回值的 `second` 是负环判断。实现逻辑:**几乎**没有优化的 Bellman-Ford。例子:`auto [dis, flag] = g.bellman_ford(0, 123);`## 三、SPFA定义:`std::pair<std::vector<distance>,bool> spfa(int start)`。功能:以 `start` 作为起点的最短路,返回值 `first` 满足:如果存在则为最短长度,不存在则为 $-1$。返回值的 `second` 是负环判断。实现逻辑:队列 SPFA。例子:`auto [dis, flag] = g.spfa(0);`:::::::::