跳到正文

个人记录

P4779 【模板】单源最短路径(标准版)题解

RoyLuo约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前

单源最短路径(标准版) 这题我们可以进行迪杰斯特拉算法来求最短路; 先来总结一下坑 1:e[10000][10000]一定会爆MLE(用零接矩阵)所以我们要用链式前向星 2:这题一定要用堆优化dije---不然会TLE 3:用spaf只能得32其他点会……T 那么只能用链式前向星+优先队列+dije。 首先是链式前向星:

C++
struct Edge{
	int to , money , nextt ;
};
Edge edge[200009] ;
inline void addedge(register int x ,register int y ,register int z)
{
	++cnt ;//让cnt指针指向这一个正在处理的点
	edge[cnt].to = y ;//记录a点通向的点
	edge[cnt].money = z ;//边权
	edge[cnt].nextt = head[x] ;//Ta下一个指向的
	head[x] = cnt ;//重置head
	return ;
}

继续是堆优化:

C++
struct node{
	int _dis ;
	int _pos ;
	bool operator < (const node &b) const{//重载
		return this->_dis > b._dis ;
	}
};

std::priority_queue<node> q ;

dije:

C++
inline void Init(void)
{
	for(register int i = 1 ; i <= n ; i ++)
		dis[i] = 2147483647 ;//初始化
	return ;
}

inline void dijkstra()
{
	dis[s] = 0 ;
	q.push((node){0,s}) ;
	while(!q.empty())
	{
		node t1 = q.top() ;
		q.pop();
		xx = t1._pos ;
		if(vis[xx] == 1)
		{
			xx = 0 ;
			continue ;//已访问
		}
		vis[xx] = 1 ;
		for(register int i = head[xx] ; i ; i = edge[i].nextt)//链式前向星
		{
			yy = edge[i].to ;
			if(dis[yy] > dis[xx] + edge[i].money)//松弛
			{
				dis[yy] = dis[xx] + edge[i].money ;
				if(vis[yy] == 0)
				{
					q.push((node){dis[yy] , yy}) ;//入队
				}
			}
		}
	}
	return ;
}

现在来看一张图 0-> 1 w=-1 0 ->2 w= 2 2-> 3 w= -2 2-> 4 w= 1 1 ->3 w= -8 3-> 2 w= -1 我们可以看到里面有—负数用dije是会WA的,因为从2开始到别的点在松弛别的点可能会设成vis[i]=1,这样是不会再改的,可是现实那么残忍:最短路不是这一条!!!!因此会WWW? 在拿一张图 0->1 w=3 0->2 w=4 0->3 w=2 1->2 w = 3 4->3 w=9 现在没负权路了。 0.标记 1.从0点开始可松弛123为342 2、接着入队 3.123松弛别的节点 4.重复以上至(!q.empty)不能走了 你现在懂了吧!!! 最后就能求出路径了 剩余代码自己想

原文