记录一个sssp算法
yeyouy
·
·
个人记录
#include <bits/stdc++.h> // 引入所有标准库头文件,方便竞赛编程
// --- Fast IO Template Start (Micro-optimized) ---
// 快速I/O模板开始(微优化版),用于加速输入输出,在处理大量数据时非常关键
#ifndef _IO // 防止头文件被重复包含
#define _IO
#if __cplusplus>=201402L // 检查C++标准版本是否至少为C++14
namespace IO { // 将快速IO相关实现封装在IO命名空间下
// 使用模板元编程(TMP)在编译期判断类型是否为有符号整数
template<typename T> struct is_signed_int {
static constexpr bool value=std::is_integral<T>::value && std::is_signed<T>::value;
};
// 使用模板元编程(TMP)在编译期判断类型是否为无符号整数
template<typename T> struct is_unsigned_int {
static constexpr bool value=std::is_integral<T>::value && std::is_unsigned<T>::value;
};
#if __SIZEOF_POINTER__==8 // 如果是64位系统,则定义128位整数类型
using i128=__int128;
using u128=__uint128_t;
// 为128位整数特化类型判断模板
template<> struct is_signed_int<i128> { static constexpr bool value=true; };
template<> struct is_unsigned_int<u128> { static constexpr bool value=true; };
#endif
// 宏定义,用于快速判断一个字符是否是数字
#define IS_DIGIT(c) ((unsigned)(c - '0') <= 9)
// 宏定义,用于快速判断一个字符是否是空白符
#define IS_SPACE(c) (c == ' ' || c == '\n' || c == '\r' || c == '\t')
// 输入缓冲区类
template<size_t S> class in_buffer {
char b[S],*p1=b; const char *p2=b; // b是缓冲区,p1是当前读取指针,p2是有效数据末尾指针
std::istream *f; // 指向输入流(如std::cin)
public:
in_buffer(std::istream *f):f(f){} // 构造函数,关联一个输入流
// 获取一个字符。如果缓冲区空了,则从流中重新读取S个字符。
char getc() { return p1!=p2 || (p2=b+f->rdbuf()->sgetn(p1=b,S))!=b?*(p1++):EOF; }
};
// 输出缓冲区类
template<size_t S> class out_buffer {
char b[S],*p1=b; // b是缓冲区,p1是当前写入指针
std::ostream *f; // 指向输出流(如std::cout)
public:
out_buffer(std::ostream *f):f(f){} // 构造函数,关联一个输出流
// 放入一个字符。如果缓冲区满了,则将整个缓冲区内容写入流中。
void putc(const char x) { if(p1==b+S) { f->rdbuf()->sputn(p1=b,S); p1=b; } *(p1++)=x; }
// 析构函数,在对象销毁时将缓冲区内剩余的内容刷入流中
~out_buffer() { f->rdbuf()->sputn(b,p1-b); }
};
// 自定义输入流类
template<size_t S> class my_istream {
using is=my_istream; // 类型别名
in_buffer<S> *const f; // 指向输入缓冲区的指针
// 读取无符号整数
template<typename T> void rdu(T &x)const{
char c; for(c=f->getc();!IS_DIGIT(c);c=f->getc()){} // 跳过前导空白符
for(x=0;IS_DIGIT(c);c=f->getc()) { x=x*10+(c&15); } // (c&15) 等价于 (c-'0'),但可能更快
}
// 读取有符号整数
template<typename T> void rds(T &x)const{
bool m=0; char c; for(c=f->getc();!IS_DIGIT(c);c=f->getc()) { m|=c==45; } // 处理负号
for(x=0;IS_DIGIT(c);c=f->getc()) { x=x*10+(c&15); }
if(m) { x=-x; }
}
// 读取单个字符
void rdc(char &x)const{ for(x=f->getc();IS_SPACE(x);x=f->getc()){} } // 跳过空白符
// 读取C风格字符串
void rdcs(char *s)const{
char c; for(c=f->getc();IS_SPACE(c);c=f->getc()){} // 跳过前导空白
for(;~c && !IS_SPACE(c);c=f->getc()) { *(s++)=c; } // 读取直到下一个空白或文件尾
*s=0; // 添加字符串结束符
}
// 读取std::string
void rdstr(std::string &s)const{
char c; for(c=f->getc();IS_SPACE(c);c=f->getc()){} // 跳过前导空白
s.clear();
for(;~c && !IS_SPACE(c);c=f->getc()) { s+=c; } // 读取直到下一个空白或文件尾
}
public:
my_istream(in_buffer<S> *f):f(f){} // 构造函数
// 利用SFINAE(替换失败并非错误)和模板重载 `>>` 操作符,根据类型选择合适的读取函数
template<typename T,typename std::enable_if<is_unsigned_int<T>::value, int>::type = 0>
friend is operator>>(const is f,T &x) { f.rdu(x); return f; }
template<typename T,typename std::enable_if<is_signed_int<T>::value, int>::type = 0>
friend is operator>>(const is f,T &x) { f.rds(x); return f; }
friend is operator>>(const is f,char &x) { f.rdc(x); return f;}
friend is operator>>(const is f,char *s) { f.rdcs(s); return f; }
friend is operator>>(const is f,std::string &s) { f.rdstr(s); return f; }
};
// 自定义输出流类
template<size_t S> class my_ostream {
using os=my_ostream; // 类型别名
out_buffer<S> *const f; // 指向输出缓冲区的指针
char T_str[20]; // 用于整数转字符串的临时空间
// 递归方式打印无符号整数
template<class T> void pr(const T x)const{
if(x>9) { pr(x/10); }
f->putc((x%10)|48); // (x%10)|48 等价于 (x%10)+'0'
}
public:
my_ostream(out_buffer<S> *f):f(f){} // 构造函数
// 利用SFINAE重载 `<<` 操作符
template<typename T,typename std::enable_if<is_unsigned_int<T>::value, int>::type = 0>
friend os operator<<(const os f,const T x) { if (x==0) f.f->putc('0'); else f.pr(x); return f; }
template<typename T,typename std::enable_if<is_signed_int<T>::value, int>::type = 0>
friend os operator<<(const os f,const T x)
{ if (x<0) { f.f->putc(45); f.pr(-x); } else if (x==0) { f.f->putc('0'); } else { f.pr(x); } return f; }
friend os operator<<(const os f,const char x) { f.f->putc(x); return f; }
friend os operator<<(const os f,const char *s) {
for(;*s;) { f.f->putc(*(s++)); } return f;
}
friend os operator<<(const os f,const std::string &s) {
for(auto x:s) { f.f->putc(x); } return f;
}
};
}
#define with_buffer // 宏开关,决定是否启用快速IO
#ifdef with_buffer
namespace IO {
static constexpr size_t IS=1<<16,OS=1<<16; // 定义输入输出缓冲区大小为64KB
in_buffer<IS> stdin_buf(&std::cin); // 创建与std::cin关联的输入缓冲区
my_istream<IS> my_cin(&stdin_buf); // 创建自定义输入流
out_buffer<OS> stdout_buf(&std::cout); // 创建与std::cout关联的输出缓冲区
my_ostream<OS> my_cout(&stdout_buf); // 创建自定义输出流
// 关键优化:解除 C++ 流与 C 标准IO的同步,并取消cin和cout的绑定
int _SYNC_WITH_STDIO_0=(std::cin.tie(0)->sync_with_stdio(0),0);
}
using IO::my_cin; // 将自定义流引入全局命名空间
using IO::my_cout;
#define cin my_cin // 用宏将 cin 和 cout 替换为自定义的流,实现无缝切换
#define cout my_cout
#endif
#endif
#endif
// --- Fast IO Template End ---
// --- 全局设定 ---
using ll = long long; // 定义ll为long long的别名,方便书写
// **优化点**: 使用一个更小但安全的INF值。`1LL << 62` 足够大,且 `INF + weight` 不会溢出 `long long`。
const ll INF = (1LL << 62);
// --- 数据结构定义 ---
struct Edge { // 定义边的结构体
int to; // 边的终点
int weight; // 边的权重
};
// --- 高级优化技巧:自定义内存池 (Arena Allocator) ---
// 内存池用于一次性申请大块内存,然后手动在其中分配小对象。
// 这避免了频繁调用 `new` 的开销,并提高了缓存局部性。
class Arena {
private:
static const size_t ARENA_SIZE = 1024 * 1024 * 128; // 预分配128MB内存
char* buffer; // 指向内存块的指针
size_t offset = 0; // 当前已分配到的位置
public:
Arena() { buffer = new char[ARENA_SIZE]; } // 构造时申请内存
~Arena() { delete[] buffer; } // 析构时释放内存
// 删除拷贝构造和赋值操作,防止内存池被意外复制
Arena(const Arena&) = delete;
Arena& operator=(const Arena&) =delete;
// 分配函数模板,可接受任意类型和构造函数参数
template<typename T, typename... Args>
T* alloc(Args&&... args) {
// 计算对齐后的偏移量,确保分配的地址符合类型T的对齐要求
size_t aligned_offset = (offset + alignof(T) - 1) & ~(alignof(T) - 1);
// 检查内存是否足够
if (aligned_offset + sizeof(T) > ARENA_SIZE) {
throw std::bad_alloc(); // 内存不足则抛出异常
}
// 使用 placement new 在buffer的指定位置构造对象 T
T* ptr = new (buffer + aligned_offset) T(std::forward<Args>(args)...);
// 更新偏移量
offset = aligned_offset + sizeof(T);
return ptr; // 返回构造好的对象的指针
}
};
// --- 优化: 紧凑化图表示 (CSR-like) ---
// 类似于压缩稀疏行(Compressed Sparse Row)的格式,将所有边存储在一个连续数组中。
// 这种方式访问一个顶点的所有邻边时,内存访问是连续的,缓存效率极高。
struct Graph {
int V, E; // 顶点数和边数
std::vector<Edge> edge_pool; // 存储所有边的"边池"
std::vector<int> head; // head[i]存储顶点i的第一条边的在edge_pool中的索引
// 构造函数,从原始边列表构建图
Graph(int n, int m, const std::vector<std::tuple<int, int, int>>& raw_edges)
: V(n), E(m), head(n + 2, 0) {
edge_pool.resize(m);
// 第一遍:统计每个顶点的出度,结果暂存在head数组中
for (const auto& edge : raw_edges) {
head[std::get<0>(edge) + 1]++;
}
// 第二遍:计算前缀和,将head[i]转换为顶点i的边在edge_pool中的起始索引
for (int i = 1; i <= n + 1; ++i) {
head[i] += head[i-1];
}
// 第三遍:填充edge_pool。head_copy用作临时指针,指示下一个要填充的位置。
std::vector<int> head_copy = head;
for (const auto& edge : raw_edges) {
int u, v, w;
std::tie(u, v, w) = edge;
// 将边 {v, w} 放入 u 的边列表的下一个可用位置
edge_pool[head_copy[u]++] = {v, w};
}
}
};
// --- 第2.3章:为批量处理设计的特制数据结构 (工程优化版) ---
// `Block` 是一个最小二叉堆,用于存储一部分待处理的顶点。
// **优化点**: 手写内联二叉堆,替换std::push_heap/pop_heap,减少函数调用开销。
struct Block {
std::vector<std::pair<ll, int>> a; // 用vector存储堆元素(距离,顶点编号)
// 向堆中插入元素 (上浮操作)
inline void push(ll d, int v) {
a.emplace_back(d,v);
int i = (int)a.size()-1; // 新元素位置
while (i>0) {
int p=(i-1)>>1; // 父节点位置
if (a[p].first <= a[i].first) break; // 如果父节点更小或相等,则停止
std::swap(a[p],a[i]); i=p; // 否则与父节点交换
}
}
// 弹出堆顶最小元素 (下沉操作)
inline std::pair<ll, int> pop_min() {
auto ret=a.front(); // 保存堆顶元素
auto x=a.back(); a.pop_back(); // 将最后一个元素移到堆顶
if (!a.empty()) {
a[0]=x;
int i=0;
while (true) {
int l=i*2+1; if (l>=(int)a.size()) break; // 左孩子
int r=l+1; int s=l; // 右孩子和较小的孩子
if (r<(int)a.size() && a[r].first < a[l].first) s=r;
if (a[s].first >= a[i].first) break; // 如果孩子节点更大,则停止
std::swap(a[i], a[s]); i=s; // 否则与较小的孩子交换
}
}
return ret;
}
bool empty() const { return a.empty(); } // 判断是否为空
ll min_key() const { return a.empty() ? INF : a.front().first; } // 返回最小元素的键(距离)
};
// 红黑树中存储的键,包含一个Block的最小距离和指向该Block的指针
struct BlockKey {
ll key; // Block中当前的最小距离
Block* ptr; // 指向Block对象的指针
// **优化点**: 转换为uintptr_t进行比较,更严谨。
// 重载比较运算符,用于在红黑树中排序。先按key(距离)排,距离相同则按指针地址排。
bool operator<(const BlockKey& other) const {
if (key != other.key) return key < other.key;
return (uintptr_t)ptr < (uintptr_t)other.ptr;
}
bool operator>(const BlockKey& other) const {
if (key != other.key) return key > other.key;
return (uintptr_t)ptr > (uintptr_t)other.ptr;
}
};
// **优化点**: 使用uint8_t代替enum,减小节点体积,提高缓存效率
struct RBNode { // 红黑树节点
BlockKey key; // 节点存储的键
RBNode *parent = nullptr, *left = nullptr, *right = nullptr; // 父、左、右孩子指针
uint8_t color = 1; // 颜色: 1代表红色, 0代表黑色
RBNode(const BlockKey& k) : key(k) {}
};
// 红黑树,用作Block的索引,可以快速找到最小距离最小的Block
class RedBlackTree {
private:
RBNode* root; // 树的根节点
RBNode* T_NIL; // 哨兵节点,代表所有叶子节点,简化边界处理
Arena& arena; // 引用内存池,所有节点都在此分配
// 左旋
void leftRotate(RBNode* x) {
RBNode* y = x->right; x->right = y->left;
if (y->left != T_NIL) { y->left->parent = x; }
y->parent = x->parent;
if (x->parent == T_NIL) { root = y; }
else if (x == x->parent->left) { x->parent->left = y; } else { x->parent->right = y; }
y->left = x; x->parent = y;
}
// 右旋
void rightRotate(RBNode* x) {
RBNode* y = x->left; x->left = y->right;
if (y->right != T_NIL) { y->right->parent = x; }
y->parent = x->parent;
if (x->parent == T_NIL) { root = y; }
else if (x == x->parent->right) { x->parent->right = y; } else { x->parent->left = y; }
y->right = x; x->parent = y;
}
// 插入后修复红黑树性质
void insertFixup(RBNode* k) {
RBNode* u;
while (k->parent->color == 1) { // 父节点是红色
RBNode* p = k->parent; RBNode* gp = p->parent;
if (p == gp->right) { // 父节点是祖父节点的右孩子
u = gp->left; // u是叔叔节点
if (u->color == 1) { // Case 1: 叔叔是红色
u->color = 0; p->color = 0; gp->color = 1; k = gp;
} else { // Case 2 & 3: 叔叔是黑色
if (k == p->left) { // Case 2: k是父节点的左孩子(需要先右旋)
k = p; rightRotate(k);
}
// Case 3: k是父节点的右孩子
k->parent->color = 0; k->parent->parent->color = 1; leftRotate(k->parent->parent);
}
} else { // 父节点是祖父节点的左孩子(对称情况)
u = gp->right;
if (u->color == 1) {
u->color = 0; p->color = 0; gp->color = 1; k = gp;
} else {
if (k == p->right) {
k = p; leftRotate(k);
}
k->parent->color = 0; k->parent->parent->color = 1; rightRotate(k->parent->parent);
}
}
if (k == root) { break; }
}
root->color = 0; // 根节点永远是黑色
}
// 用v子树替换u子树
void transplant(RBNode* u, RBNode* v) {
if (u->parent == T_NIL) { root = v; }
else if (u == u->parent->left) { u->parent->left = v; } else { u->parent->right = v; }
v->parent = u->parent;
}
// 寻找子树中的最小节点
RBNode* minimum(RBNode* node) {
while (node->left != T_NIL) { node = node->left; }
return node;
}
// 删除后修复红黑树性质
void removeFixup(RBNode* x) {
RBNode* s;
while (x != root && x->color == 0) { // x是双黑节点
if (x == x->parent->left) { // x是左孩子
s = x->parent->right; // s是兄弟节点
if (s->color == 1) { /* Case 1 */ s->color = 0; x->parent->color = 1; leftRotate(x->parent); s = x->parent->right; }
if (s->left->color == 0 && s->right->color == 0) { /* Case 2 */ s->color = 1; x = x->parent; }
else {
if (s->right->color == 0) { /* Case 3 */ s->left->color = 0; s->color = 1; rightRotate(s); s = x->parent->right; }
/* Case 4 */ s->color = x->parent->color; x->parent->color = 0; s->right->color = 0; leftRotate(x->parent); x = root;
}
} else { // x是右孩子(对称情况)
s = x->parent->left;
if (s->color == 1) { s->color = 0; x->parent->color = 1; rightRotate(x->parent); s = x->parent->left; }
if (s->right->color == 0 && s->left->color == 0) { s->color = 1; x = x->parent; }
else {
if (s->left->color == 0) { s->right->color = 0; s->color = 1; leftRotate(s); s = x->parent->left; }
s->color = x->parent->color; x->parent->color = 0; s->left->color = 0; rightRotate(x->parent); x = root;
}
}
}
x->color = 0;
}
public:
RedBlackTree(Arena& a) : arena(a) { // 构造函数
// 从内存池分配哨兵节点并初始化
T_NIL = arena.alloc<RBNode>(BlockKey{INF, nullptr});
T_NIL->color = 0; T_NIL->left = T_NIL; T_NIL->right = T_NIL; root = T_NIL;
}
// 插入一个键
void insert(const BlockKey& key) {
RBNode* node = arena.alloc<RBNode>(key); // 从内存池分配新节点
node->parent = T_NIL; node->left = T_NIL; node->right = T_NIL;
RBNode* y = T_NIL; RBNode* x = this->root;
while (x != T_NIL) { // 寻找插入位置
y = x;
if (node->key < x->key) { x = x->left; } else { x = x->right; }
}
node->parent = y; // 链接新节点
if (y == T_NIL) { root = node; }
else if (node->key < y->key) { y->left = node; } else { y->right = node; }
if (node->parent == T_NIL) { node->color = 0; return; }
if (node->parent->parent == T_NIL) { return; }
insertFixup(node); // 修复性质
}
RBNode* findMin() { return minimum(root); } // 找到整棵树的最小键
// 查找一个键对应的节点
RBNode* find(const BlockKey& key) {
RBNode* node = root;
while(node != T_NIL) {
if (key < node->key) { node = node->left; }
else if (key > node->key) { node = node->right; }
else { return node; } // 找到
}
return T_NIL; // 未找到
}
// 删除一个键
void remove(const BlockKey& key) {
RBNode* z = find(key); if (z == T_NIL) { return; } // 找不到则不删除
RBNode* x, *y = z; uint8_t y_original_color = y->color;
if (z->left == T_NIL) { x = z->right; transplant(z, z->right); } // z最多有一个孩子
else if (z->right == T_NIL) { x = z->left; transplant(z, z->left); }
else { // z有两个孩子
y = minimum(z->right); // y是z的后继
y_original_color = y->color; x = y->right;
if (y->parent == z) { x->parent = y; }
else { transplant(y, y->right); y->right = z->right; y->right->parent = y; }
transplant(z, y); y->left = z->left; y->left->parent = y; y->color = z->color;
}
if (y_original_color == 0) { removeFixup(x); } // 如果删除的是黑色节点,需要修复
}
bool empty() const { return root == T_NIL; } // 判断树是否为空
};
// 批量优先队列:一个“优先队列的优先队列”
// 它由多个Block(小优先队列)组成,并用一个红黑树来索引这些Block。
class BatchPriorityQueue {
private:
Arena& arena; // 内存池引用
RedBlackTree block_index; // 索引Block的红黑树
size_t total_size = 0; // 队列中元素的总数
public:
BatchPriorityQueue(Arena& a) : arena(a), block_index(a) {} // 构造函数
// 插入一个Block
void insert_block(Block* b) {
if (!b->empty()) {
// 将Block的最小键和指针作为key,插入到红黑树中
block_index.insert({b->min_key(), b});
total_size += b->a.size();
}
}
// 从队列中拉取(pull)最多M个最小的元素
std::pair<std::vector<int>, ll> pull(int M) {
std::vector<int> pulled_vertices; ll upper_bound = INF;
if (empty()) return {pulled_vertices, upper_bound};
for (int i = 0; i < M && !empty(); ++i) {
// 懒惰更新循环:检查红黑树顶端的Block信息是否过时
while (true) {
if (block_index.empty()) break;
RBNode* min_node = block_index.findMin();
// 如果Block已空,或者它在红黑树中的key与其实际最小key不符,说明信息过时
if (min_node->key.ptr->empty() || min_node->key.key != min_node->key.ptr->min_key()) {
Block* ptr = min_node->key.ptr; BlockKey old_key = min_node->key;
block_index.remove(old_key); // 删除旧的key
if (!ptr->empty()) block_index.insert({ptr->min_key(), ptr}); // 插入更新后的key
continue; // 继续检查,直到找到一个信息准确的Block
}
break; // 信息准确,退出循环
}
if (block_index.empty()) break;
// 弹出全局最小元素
RBNode* min_node = block_index.findMin();
Block* min_block = min_node->key.ptr;
auto min_element = min_block->pop_min(); // 从最小的Block中弹出元素
pulled_vertices.push_back(min_element.second);
total_size--;
// 更新该Block在红黑树中的索引
BlockKey old_key = min_node->key;
block_index.remove(old_key);
if (!min_block->empty()) {
block_index.insert({min_block->min_key(), min_block});
}
}
// 再次进行懒惰更新,以获取当前队列中准确的最小距离作为下次递归的上界
if (!block_index.empty()) {
while (true) {
if (block_index.empty()) break;
RBNode* min_node = block_index.findMin();
if (min_node->key.ptr->empty() || min_node->key.key != min_node->key.ptr->min_key()) {
Block* ptr = min_node->key.ptr; BlockKey old_key = min_node->key;
block_index.remove(old_key);
if (!ptr->empty()) block_index.insert({ptr->min_key(), ptr});
continue;
}
upper_bound = min_node->key.key; // 找到准确的最小值
break;
}
}
return {pulled_vertices, upper_bound}; // 返回拉取的顶点和新的距离上界
}
bool empty() const { return total_size == 0; } // 判断队列是否为空
};
// --- 最终优化:Radix Heap ---
// 基数堆是一种专为Dijkstra算法设计的优先队列,当边权为非负整数时效率极高。
// 它利用距离的二进制表示,将节点放入不同的“桶”中。
// **优化点**: 桶用std::vector,合并top/pop,简化逻辑
class RadixHeap {
private:
static const int BIT_WIDTH = 64; // 处理64位整数距离
std::vector<std::pair<ll, int>> buckets[BIT_WIDTH + 1]; // 65个桶
ll last_dist; // 上一个弹出的最小距离
size_t count; // 堆中元素总数
// 内联函数,快速计算一个数与last_dist的异或结果的最高有效位(MSB)
// `__builtin_clzll`是GCC/Clang内建函数,计算前导零的数量
inline int get_msb_pos(ll n) {
return n == 0 ? -1 : 63 - __builtin_clzll(n);
}
public:
RadixHeap() : last_dist(0), count(0) {}
bool empty() const { return count == 0; }
// 入队操作
inline void push(ll distance, int vertex) {
count++;
// 计算应该放入哪个桶:根据`distance`和`last_dist`的异或值的MSB位置
int b_idx = get_msb_pos(distance ^ last_dist) + 1;
buckets[b_idx].emplace_back(distance, vertex);
}
// 出队操作(合并了top和pop)
inline std::pair<ll, int> top_and_pop() {
// 如果0号桶(距离与last_dist差异最小的桶)为空,则需要重分配
if (buckets[0].empty()) {
int i = 1;
while (buckets[i].empty()) { i++; } // 找到下一个非空桶
// 在这个非空桶中找到最小的距离,更新last_dist
last_dist = buckets[i][0].first;
for(size_t j = 1; j < buckets[i].size(); ++j) {
if(buckets[i][j].first < last_dist) {
last_dist = buckets[i][j].first;
}
}
// 将该桶中所有元素根据新的last_dist重新分配到各个桶
std::vector<std::pair<ll, int>> temp_bucket;
buckets[i].swap(temp_bucket);
for (const auto& p : temp_bucket) {
int b_idx = get_msb_pos(p.first ^ last_dist) + 1;
buckets[b_idx].push_back(p);
}
}
// 从0号桶中弹出一个元素(0号桶中任意元素都是当前最小距离之一)
auto ret = buckets[0].back();
buckets[0].pop_back();
count--;
return ret;
}
};
// --- 核心算法逻辑 ---
// 迭代版本的DFS,用于计算最短路径树中每个节点的后代数量
void count_descendants_iter(int root, const std::vector<std::vector<int>>& g, std::vector<int>& sizes, std::vector<bool>& visited) {
if (visited[root]) return;
std::vector<int> st; st.reserve(64); st.push_back(root); // 显式栈
std::vector<int> order; order.reserve(g.size()); // 存储DFS访问顺序
// 第一次遍历:生成拓扑序(后序遍历的逆序)
while (!st.empty()) {
int u = st.back(); st.pop_back();
if (visited[u]) continue;
visited[u] = true;
order.push_back(u);
for (int v : g[u]) if (!visited[v]) st.push_back(v);
}
// 第二次遍历:按后序遍历的顺序,从叶子节点开始计算子树大小
for (auto it = order.rbegin(); it != order.rend(); ++it) {
int u = *it;
sizes[u] = 1;
for (int v : g[u]) sizes[u] += sizes[v];
}
}
// **优化点**: 1. 内联 2. 使用指针迭代 3. 使用top_and_pop 4. 简化松弛
// 使用RadixHeap的Dijkstra算法
inline void dijkstra(const std::vector<int>& sources, const Graph& adj, std::vector<ll>& dist) {
RadixHeap pq;
// 将所有源点加入优先队列
for (int s : sources) {
if (dist[s] < INF) pq.push(dist[s], s);
}
while (!pq.empty()) {
auto [d, u] = pq.top_and_pop(); // 取出最小元
if (d > dist[u]) continue; // 如果是旧的、更长的距离,则跳过
// 使用指针迭代邻边,比用索引更快
const Edge* e_ptr = &adj.edge_pool[adj.head[u]];
const Edge* e_end = &adj.edge_pool[adj.head[u + 1]];
while (e_ptr != e_end) {
const Edge& edge = *e_ptr;
ll new_dist = d + edge.weight;
if (new_dist < dist[edge.to]) { // 松弛操作
dist[edge.to] = new_dist;
pq.push(new_dist, edge.to);
}
e_ptr++;
}
}
}
// **优化点**: 使用指针迭代,简化松弛
// 寻找“枢轴点”(pivots)和“已完成”的顶点
// 这是一个类似Bellman-Ford的k轮松弛过程
std::pair<std::vector<int>, std::vector<int>> find_pivots(
const std::vector<int>& S, // 当前的源点集
const Graph& adj,
std::vector<ll>& dist,
int k // 松弛轮数
) {
int V = adj.V + 1;
// 使用时间戳来避免在每轮中重复将顶点加入next_frontier
static std::vector<int> timestamp;
static int time_counter = 0;
if (static_cast<int>(timestamp.size()) < V) timestamp.resize(V, 0);
std::vector<ll> dists[2]; // 使用两个数组滚动记录距离
std::vector<int> preds[2]; // 记录前驱节点
dists[0] = dist; dists[1] = dist;
preds[0].assign(V, -1); preds[1].assign(V, -1);
// 初始边界(frontier)是源点集S
std::vector<int> frontier = S;
frontier.erase(std::remove_if(frontier.begin(), frontier.end(), [&](int u){ return dist[u] >= INF; }), frontier.end());
int read_idx = 0; // 当前读取的距离数组索引
for (int i = 1; i <= k; ++i) { // 进行k轮松弛
int write_idx = 1 - read_idx; // 写入的距离数组索引
std::vector<int> next_frontier; // 下一轮的边界
next_frontier.reserve(frontier.size());
time_counter++;
// 对当前边界中的每个点进行松弛
for (int u : frontier) {
if (dists[read_idx][u] < INF) {
const Edge* e_ptr = &adj.edge_pool[adj.head[u]];
const Edge* e_end = &adj.edge_pool[adj.head[u + 1]];
while (e_ptr != e_end) {
const Edge& edge = *e_ptr;
ll new_dist = dists[read_idx][u] + edge.weight;
if (new_dist < dists[write_idx][edge.to]) {
dists[write_idx][edge.to] = new_dist;
preds[write_idx][edge.to] = u;
if (timestamp[edge.to] != time_counter) {
next_frontier.push_back(edge.to);
timestamp[edge.to] = time_counter;
}
}
e_ptr++;
}
}
}
read_idx = write_idx; // 滚动数组
frontier = std::move(next_frontier); // 更新边界
if (frontier.empty()) break; // 如果没有可以松弛的边,提前结束
}
std::vector<ll>& dist_k = dists[read_idx]; // k轮后的距离
std::vector<ll>& dist_k_minus_1 = dists[1 - read_idx]; // k-1轮后的距离
std::vector<int>& pred_k = preds[read_idx]; // k轮后的前驱
dist = dist_k; // 更新全局距离数组
std::vector<int> completed_vertices; // 记录已完成的顶点
// 如果一个顶点在第k轮没有被松弛,说明它已经找到了长度不超过k的最短路
for (int v = 1; v < V; ++v) {
if (dist_k_minus_1[v] == dist_k[v]) completed_vertices.push_back(v);
}
// 根据前驱数组构建最短路径树
std::vector<std::vector<int>> sp_tree_adj(V);
for (int v = 1; v < V; ++v) {
if (pred_k[v] != -1) sp_tree_adj[pred_k[v]].push_back(v);
}
// 计算每个源点在最短路径树中的后代数量
std::vector<int> sizes(V, 0);
std::vector<bool> visited(V, false);
for (int u : S) {
if (!visited[u]) count_descendants_iter(u, sp_tree_adj, sizes, visited);
}
// 后代数量超过k的源点被选为“枢轴点”
std::vector<int> pivots;
for (int u : S) {
if (sizes[u] >= k) pivots.push_back(u);
}
return {pivots, completed_vertices};
}
// BMSSP (Batch Multi-source Shortest Path) 核心递归函数
void bmssp(
Arena& arena, int l, const std::vector<int>& S, ll B,
const Graph& adj, std::vector<ll>& dist,
int k, int t, int dijkstra_threshold
) {
if (S.empty()) return; // 基线条件:源点集为空
// 基线条件:递归层数耗尽,或源点集太小,直接调用Dijkstra解决
if (l == 0 || S.size() <= static_cast<size_t>(dijkstra_threshold)) {
dijkstra(S, adj, dist);
return;
}
// 递归步骤:
// 1. 寻找枢轴点和已完成顶点
auto result = find_pivots(S, adj, dist, k);
std::vector<int> pivots = result.first;
std::vector<int> completed_vertices = result.second;
// 2. 对已完成的顶点运行Dijkstra,最终确定它们的距离
dijkstra(completed_vertices, adj, dist);
// 3. 将枢轴点分批放入批量优先队列
BatchPriorityQueue pq(arena);
// 动态计算分组大小,以控制Block的数量
const int target_blocks = std::max(1, std::min(1024, (int)pivots.size() / 8));
const int group_size = std::max(1, (int)ceil((double)pivots.size() / target_blocks));
for (size_t i = 0; i < pivots.size(); i += group_size) {
Block* b = arena.alloc<Block>(); // 从内存池分配一个Block
b->a.reserve(group_size);
for (size_t j = i; j < i + group_size && j < pivots.size(); ++j) {
int p = pivots[j];
if (dist[p] < B) b->push(dist[p], p); // 距离小于上界B的枢轴点才加入
}
if (!b->empty()) pq.insert_block(b); // 将Block插入批量优先队列
}
// 4. 循环处理批量优先队列中的枢轴点
while (!pq.empty()) {
int M = std::max(1, (int)(pivots.size() / t)); // 每次拉取的批次大小
auto pull_result = pq.pull(M);
std::vector<int> pulled_pivots = pull_result.first; // 拉取出的枢轴点
ll next_B = pull_result.second; // 队列中剩余元素的最小距离
if (pulled_pivots.empty()) break;
ll recursive_B = std::min(B, next_B); // 计算下次递归的距离上界
// 5. 对拉取出的枢轴点进行递归调用
bmssp(arena, l - 1, pulled_pivots, recursive_B, adj, dist, k, t, dijkstra_threshold);
}
}
// 新的SSSP求解器入口
void new_sssp_solver(int n, int s, const Graph& adj, std::vector<ll>& dist) {
dist.assign(n + 1, INF);
dist[s] = 0;
// 根据图的大小n动态计算算法的超参数k, t, l_max
double log_n = std::log2(n > 1 ? n : 2);
int k = std::max(1, static_cast<int>(std::pow(log_n, 1.0/3.0) + 0.5));
int t = std::max(1, static_cast<int>(std::pow(log_n, 2.0/3.0) + 0.5));
int l_max = (t > 0) ? std::max(1, static_cast<int>(log_n / t + 0.5)) : 1;
// **优化点**: 自适应阈值,用于决定何时从递归切换到普通Dijkstra
int dijkstra_threshold = std::max(64, std::min(256, n / 500));
Arena arena; // 创建一个内存池供整个算法使用
// 启动BMSSP递归算法
bmssp(arena, l_max, {s}, INF, adj, dist, k, t, dijkstra_threshold);
}
int main() {
int n, m, s; // n:顶点数, m:边数, s:源点
cin >> n >> m >> s;
// 读取所有边
std::vector<std::tuple<int, int, int>> raw_edges;
raw_edges.reserve(m);
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
raw_edges.emplace_back(u, v, w);
}
// 构建CSR格式的图
Graph adj(n, m, raw_edges);
// 调用求解器计算最短路
std::vector<ll> dist;
new_sssp_solver(n, s, adj, dist);
// 输出结果,对于不可达点,按题目要求输出特定值
const int unreachable_output = 2147483647;
for (int i = 1; i <= n; ++i) {
if (dist[i] >= INF) {
cout << unreachable_output;
} else {
cout << dist[i];
}
if (i < n) cout << " ";
}
cout << '\n';
return 0;
}