跳到正文

算法·理论

最短路学习笔记

云裳约 31 分钟
原文
文章信息与版本

文章信息

发布
2023年8月15日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 31 分钟
获赞
1

版本

  1. v1当前

Floyd

特点

  • 用以求解多源最短路。
  • 可以有向图或无向图。
  • 可以处理负边权。
  • 代码短,时间复杂度高,为 O(n3)O(n^3)。

算法流程

每次考虑前 kk 个点中点对 (i,j)(i,j) 能不能达到和 (i,j)(i,j) 的最短路,kk 依次递增。

设 disi,jdis_{i,j} 为当前 (i,j)(i,j) 的最短路,fi,jf_{i,j} 为 ii 能否到达 jj。如果 fi,k=fk,j=1f_{i,k}=f_{k,j}=1,那么转移, disi,j=min⁡(disi,j,disi,k+disk,j),fi,j=1dis_{i,j}=\min(dis_{i,j},dis_{i,k}+dis{k,j}),f_{i,j}=1,也就是每次跟中转点比较,尝试转移。

初始时,disi,i=0,fi,i=1dis_{i,i}=0,f_{i,i}=1,其他 disi,j=∞,fi,j=0dis_{i,j}=\infty,f_{i,j}=0。每输入 ii 到 jj 的距离为 kk,就将 disi,jdis_{i,j} 记录为 kk,fi,jf_{i,j} 记录为 11,无向图就反过来再记录一次。


模板代码

C++
#include <bits/stdc++.h>
#define up(i, l, r) for (int i = l, END##i = r; i <= END##i; i++)
#define dn(i, r, l) for (int i = r, END##i = l; i >= END##i; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF = 0x3f3f3f3f, N = 207;
ll dis[N][N];
bool f[N][N];
namespace sol {
void solve() {
    ll n, m;
    cin >> n >> m;
    memset(dis, 127, sizeof dis);
    up(i, 1, n) dis[i][i] = 0;
    while (m--) {
        ll x, y, z;
        cin >> x >> y >> z;
        dis[x][y] = dis[y][x] = min(dis[x][y], z);
        f[x][y] = f[y][x] = 1;
  	//注意是无向图,要反过来再记录一遍
    }
    up(k, 1, n) {
        up(i, 1, n) {
            up(j, 1, n) {
                if (f[i][k] && f[k][j]) {//判断能否中转
                    f[i][j] = 1;
                    dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
                }
            }
        }
    }
    up(i, 1, n) {
        up(j, 1, n) cout << dis[i][j] << " ";
        cout << "\n";
    }
}
} // namespace sol
using namespace sol;
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    solve();
    return 0;
}

Dijkstra

特点

  • 可以处理有向图、无向图
  • 时间较快,用优先队列优化为 O(mlog⁡m)O(m \log m)
  • 不能处理负边权
  • 多求解单元最短路,要求多源的话就重复做几次

算法流程

设 disidis_i 为源点 ss 到 ii 的最短路。

  1. 初始化 diss=0dis_s=0,其它均为 ∞\infty。
  2. 在已经求出 disdis 的点中选一个即 disxdis_x 最小点 ,并给 xx 打上标记保证以后不再取出。
  3. 扫描 xx 的所有出边去更新其他点,并将它们入队。
  4. 重复步骤 22、33 直至所有点均入过队列。

模板代码

C++
#include<bits/stdc++.h>
#define up(i,l,r) for(int i=l,END##i=r;i<=END##i;i++)
#define dn(i,r,l) for(int i=r,END##i=l;i>=END##i;i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF=0x3f3f3f3f,N=1e5+7,M=2e5+7;
struct e {
	ll nxt,w,to;
} a[M];
struct node {
	ll x,w;
	bool operator<(const node o)const {
		return w>o.w;//重载运算符,每次查询最小值
	}
};
bool f[N];//是否加入过队列
ll head[N],tot;
void add(ll x,ll y,ll z) {
	a[++tot].to=y,a[tot].w=z,a[tot].nxt=head[x],head[x]=tot;
}
priority_queue<node> q;
ll n,m,s;
ll dis[N];
namespace sol {
	void solve() {
		cin>>n>>m>>s;
		memset(dis,63,sizeof dis);
		dis[s]=0;
		q.push((node) {
			s,0
		});
		while(m--) {
			ll x,y,z;
			cin>>x>>y>>z;
			add(x,y,z);
		}
		while(!q.empty()) {
			node now=q.top();
			q.pop();
			ll id=now.x;
			if(f[id]) continue;//只能入队列一次
			f[id]=1;
			for(int i=head[id]; i; i=a[i].nxt) {
				ll to=a[i].to;
				if(dis[to]>dis[id]+a[i].w) {//尝试更新
					dis[to]=dis[id]+a[i].w;
					q.push((node) {
						to,dis[to]
					});
				}
			}
		}
		up(i,1,n) cout<<dis[i]<<' ';
	}
}
using namespace sol;
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(nullptr);
	solve();
	return 0;
}

练习

P4667 [BalticOI 2011 Day1] Switch the Lamp On

用最短路,先建图,求的是最小的改变次数。对于一个 \ ,可以将左上角和右下角连一个边权为 00 的边,表示不用改变就能到达;将右上角和左下角连一个边权为 11 的边,表示要改变一次才能互相到达。

然后给的是一个二维网格,而 Dijkstra 不能处理这个,就想怎么把它变成一个正常的一维图。对于点 (i,j)(i,j),可以将它映射成 (i−1)×(m+1)+j(i-1)\times (m+1)+j,用 m+1m+1 是因为每个字符的左右两边都要有,所以会多一个。

然后再正常跑一个 Dijkstra 就行了。如果在跑完之后 dis(n+1)×(m+1)dis_{(n+1)\times(m+1)} 还是 ∞\infty 就无解。用 n+1n+1 是因为每个字符的上下都要有,所以会多一行。

注意连边连的是双向边。

代码

C++
#include <bits/stdc++.h>
#include <queue>
#define up(i, l, r) for (int i = l, END##i = r; i <= END##i; i++)
#define dn(i, r, l) for (int i = r, END##i = l; i >= END##i; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF = 0x3f3f3f3f, N = 507, M = 1007, P = 1e6 + 7;
struct e {
    ll nxt, to, w;
} a[P];
struct node {
    ll x, w;
    bool operator<(const node o) const { return w > o.w; }
};
ll head[P], tot;
void add(ll x, ll y, ll z) {
    a[++tot].to = y, a[tot].w = z, a[tot].nxt = head[x], head[x] = tot;
}
priority_queue<node> q;
ll n, m, s, dis[P];
char c[N][N];
bool f[P];
namespace sol {
ll turn(ll x, ll y) { return (x - 1) * (m + 1) + y; }
void solve() {
    cin >> n >> m;
    memset(dis, 63, sizeof dis);
    ll inf = dis[0];
    s = 1;
    dis[s] = 0;
    q.push((node){s, 0});
    up(i, 1, n) up(j, 1, m) cin >> c[i][j];
    up(i, 1, n) {
        up(j, 1, m) {
            ll j_ = j;
            ll lu = turn(i, j_), ru = turn(i, j_ + 1), ld = turn(i + 1, j_),
               rd = turn(i + 1, j_ + 1);
            if (c[i][j] == '\\') {//左上和右下边权为 0,左下和右上边权为1
                add(lu, rd, 0), add(rd, lu, 0);
                add(ru, ld, 1), add(ld, ru, 1);
            } else {//左上和右下边权为 1,左下和右上边权为0
                add(lu, rd, 1), add(rd, lu, 1);
                add(ru, ld, 0), add(ld, ru, 0);
            }
        }
    }
    while (!q.empty()) {
        node now = q.top();
        q.pop();
        ll id = now.x;
        if (f[id])
            continue;
        f[id] = 1;
        for (int i = head[id]; i; i = a[i].nxt) {
            ll to = a[i].to;
            if (dis[to] > dis[id] + a[i].w)
                dis[to] = dis[id] + a[i].w, q.push((node){to, dis[to]});
        }
    }
    (dis[(n + 1) * (m + 1)] == dis[0] ? cout << "NO SOLUTION"
                                      : cout << dis[(n + 1) * (m + 1)]);
}
} // namespace sol
using namespace sol;
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    solve();
    return 0;
}

分层图

  1. P2939 [USACO09FEB] Revamping Trails G

题意

有 KK 次机会可以把某条边边权变为 00,求最短路。


解法

  1. 加状态, disi,jdis_{i,j} 表示源点 ss 到 ii,用了 jj 次机会的最短路。

每次转移要么不用,跟普通的 Dijkstra 一样;要么判断次数超不超过 KK,如果不超过 KK 就转移到 disv,k+1dis_{v,k+1},其中 vv 为 ii 连向的点。


2.用分层图。把每个节点拆分为 K+1K+1 个点,表示用多少次机会。然后再大图上连边,跑 Dijkstra。

不过由于每个节点编号已经变了,就仿照 P4667,将二维平面压成一维。

同时注意一下数组大小。每次会有 44 条连边(用机会的双向边两条,不用机会的双向边两条),因此链式前向星要开到 4×(K+1)×m≈4.5∗1064\times (K+1) \times m\approx 4.5*10^{6}。

C++
    ll turn(ll x, ll y) { return x + y * n; }
    cin >> n >> m >> k;
    memset(dis, 63, sizeof dis);
    s = 1;
    dis[s] = 0;
    q.push((node){s, 0});
    while (m--) {
        ll x, y, z;
        cin >> x >> y >> z;
        up(i, 0, k) { //枚举使用次数
            add(turn(x, i), turn(y, i), z), add(turn(y, i), turn(x, i), z);
            if (i < k)
                add(turn(x, i), turn(y, i + 1), 0),
                    add(turn(y, i), turn(x, i + 1), 0);
        }
    }
    while (!q.empty()) {
        node now = q.top();
        q.pop();
        ll id = now.x;
        if (f[id])
            continue;
        f[id] = 1;
        for (int i = head[id]; i; i = a[i].nxt) {
            ll to = a[i].to;
            if (dis[to] > dis[id] + a[i].w)
                dis[to] = dis[id] + a[i].w, q.push((node){to, dis[to]});
        }
    }
    up(i, 0, k) ans = min(ans, dis[turn(n, i)]);//可能次数用不完,因此要枚举
    cout << ans;

  1. P4011 孤岛营救问题

题意

有一个迷宫,迷宫里有墙,不能走;有不同的门,需要与之匹配的钥匙才能通过。求通过迷宫的最短路。


解法

钥匙的总量 SS 很小,小到可以通过 O(nm2s)O(nm2^{s}),因此考虑状压。

对持有的钥匙状压成 kk,kk 的二进制下第 ii 为表示有没有第 ii 种钥匙。然后就可以 BFS 了。

C++
#include <algorithm>
#include <bits/stdc++.h>

#define up(i, l, r) for (int i = l, END##i = r; i <= END##i; i++)
#define dn(i, r, l) for (int i = r, END##i = l; i >= END##i; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF = 0x3f3f3f3f, N = 13;
bool vis[N][N][1 << 15];
ll door[N][N][N][N];
vector<ll> key[N][N];//钥匙的状压
ll dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
ll n, m, p, k, s;
struct node {
    ll x, y, step, have;
};
queue<node> q;
namespace sol {
bool check(ll x, ll y) {
    if (x < 1 || y < 1 || x > n || y > m)
        return 0;
    return 1;
}
void bfs() {
    ll f = 0;
    for (auto i : key[1][1])
        f |= (1 << i - 1);
    vis[1][1][f] = 1;
    q.push((node){1, 1, 0, f});
    while (!q.empty()) {
        node now = q.front();
        q.pop();
        if (now.x == n && now.y == m) {
            cout << now.step;
            return;
        }
        up(i, 0, 3) {
            ll x = now.x + dx[i], y = now.y + dy[i],
               d = door[x][y][now.x][now.y];
            if (!check(x, y))
                continue;

            if (d == -1)

                continue;
            ll hv = now.have;
            if (d && (hv & (1 << d - 1)) == 0)
                continue;

            for (auto j : key[x][y])
                hv |= (1 << j - 1);
            if (vis[x][y][hv])
                continue;

            vis[x][y][hv] = 1;
            q.push((node){x, y, now.step + 1, hv});
        }
    }
    cout << "-1";
}
void solve() {
    cin >> n >> m >> p >> k;
    up(i, 1, k) {
        ll x1, y1, x2, y2, d;
        cin >> x1 >> y1 >> x2 >> y2 >> d;
        if (!d)
            d = -1;
        door[x1][y1][x2][y2] = door[x2][y2][x1][y1] = d;
    }
    cin >> s;
    up(i, 1, s) {
        ll x, y, q;
        cin >> x >> y >> q;
        key[x][y].push_back(q);
    }
    bfs();
}
} // namespace sol
using namespace sol;
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    solve();
    return 0;
}

最短路计数

P1144 最短路计数

在转移的时候判断一下。设节点11 到节点 ii 的最短路有 dpidp_i 条。如果在顶点 xx 转移会使 yy 的最短路的边权变小,就将 dpydp_y 变为 dpxdp_x。如果最短路边权一样,就把 dpydp_y 加上 dpxdp_x。

C++
while (!q.empty()) {
        node now = q.top();
        q.pop();
        ll id = now.x;
        if (f[id])
            continue;
        f[id] = 1;
        for (int i = head[id]; i; i = a[i].nxt) {
            ll to = a[i].to;
            if (dis[to] == dis[id] + a[i].w)
                (dp[to] += dp[id]) %= mod;
            if (dis[to] > dis[id] + a[i].w) {
                dis[to] = dis[id] + a[i].w;
                dp[to] = dp[id];
                q.push((node){to, dis[to]});
            } 
        }
    }

SPFA

特点

  • 可以处理有向图、无向图
  • 可以处理负边权
  • 可以判负环
  • 时间复杂度不如 Dijkstra 优,可能被卡,因此在无负边权的情况下使用 Dijkstra。

算法流程

  1. 初始化源点 ss 并入队,其他均为 ∞\infty。
  2. 挨个挨个取出队头 xx,扫描 xx 的所有出边去更新其他点,如果它们还没入队,就加入队列。
  3. 重复步骤 22。

注意这里的标记含义为当前在不在队列里,而 Dijkstra 是有没有入过队里。


模板代码

P3371 【模板】单源最短路径(弱化版)

C++
#include<bits/stdc++.h>
#define up(i,l,r) for(int i=l,END##i=r;i<=END##i;i++)
#define dn(i,r,l) for(int i=r,END##i=l;i>=END##i;i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF=0x3f3f3f3f,N=1e4+7,M=5e5+7;
struct e {
	ll to,nxt,w;
} a[M];
ll head[N],tot;
void add(ll x,ll y,ll z) {
	a[++tot].w=z,a[tot].to=y,a[tot].nxt=head[x],head[x]=tot;
}
ll n,m,s;
queue<ll> q;
ll dis[N];
bool f[N];
namespace sol {
	void solve() {
		cin>>n>>m>>s;
		up(i,0,n) dis[i]=INT_MAX;
		dis[s]=0;
		q.push(s);
		while(m--) {
			ll x,y,z;
			cin>>x>>y>>z;
			add(x,y,z);
		}
		while(!q.empty()) {
			ll id=q.front();
			q.pop();
			f[id]=0;//当前不在队列里
			for(int i=head[id]; i; i=a[i].nxt) {
				ll to=a[i].to;
				if(dis[to]>dis[id]+a[i].w) {
					dis[to]=dis[id]+a[i].w;
					if(!f[to]) f[to]=1,q.push(to);
				}
			}
		}
		up(i,1,n) cout<<dis[i]<<' ';
	}
}
using namespace sol;
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(nullptr);
	solve();
	return 0;
}


最长路

P1807 最长路

将边权取个负跑最短路,最后再取个负就是答案。

这时 Dijkstra 不能这样做,因为它处理不了负边权。


负环

P3385 【模板】负环

SPFA 最有用的就是可以判断负环。

注意到如果有负环会一直在环上走,因此有三种判断方式:

  1. 用松弛次数判断,但会被重边 Hack
  2. 用入队次数判断,但速度会慢一点
  3. 用经过节点次数判断,这是最好的方法

显然,方法 22 和方法 33 是判断是否大于 nn,而方法以是判断是否不小于 nn。

C++
#include<bits/stdc++.h>
#define up(i,l,r) for(int i=l,END##i=r;i<=END##i;i++)
#define dn(i,r,l) for(int i=r,END##i=l;i>=END##i;i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF=0x3f3f3f3f,N=2e3+7,M=6e3+7;
struct e {
	ll nxt,to,w;
} a[M];
bool f[N];
ll dis[N],cnt[N];//经过节点的次数
ll head[N],tot;
ll n,m,s=1;
void add(ll x,ll y,ll z) {
	a[++tot].to=y,a[tot].w=z,a[tot].nxt=head[x],head[x]=tot;
}
namespace sol {
	bool spfa() {
  //返回1表示有负环
		queue<ll> q;
		q.push(s);
		dis[s]=0,cnt[s]=1;
		while(!q.empty()) {
			ll id=q.front();
			q.pop();
			f[id]=0;
			for(int i=head[id]; i; i=a[i].nxt) {
				ll to=a[i].to;

				if(dis[to]>dis[id]+a[i].w) {
					dis[to]=dis[id]+a[i].w;
					cnt[to]=cnt[id]+1;
					if(cnt[to]>n) return 1;//最多是一条链,经过了 n 个点
					if(!f[to])f[to]=1,q.push(to);
				}

			}
		}
		return 0;
	}
	void solve() {
		cin>>n>>m;
		memset(head,0,sizeof head);
		memset(f,0,sizeof f);
		memset(cnt,0,sizeof cnt);
		memset(dis,63,sizeof dis);
		up(i,0,m) a[i].nxt=a[i].to=a[i].w=0;
		tot=0;
		while(m--) {
			ll u,v,w;
			cin>>u>>v>>w;
			add(u,v,w);
			if(w>=0) add(v,u,w);
		}
		cout<<(spfa()?"YES":"NO");
	}
}
using namespace sol;
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(nullptr);
	ll t;
	cin>>t;
	while(t--)solve(),cout<<'\n';
	return 0;
}



差分约束

P5960 【模板】差分约束算法

题意

给出一组包含 mm 个不等式,有 nn 个未知数的形如:

{xc1−xc1′≤y1xc2−xc2′≤y2⋯xcm−xcm′≤ym \begin{cases} x_{c_1}-x_{c'_1}\leq y_1 \\x_{c_2}-x_{c'_2} \leq y_2 \\ \cdots\\ x_{c_m} - x_{c'_m}\leq y_m\end{cases}

的不等式组,求解,或判无解。


解法

把每个未知数 xx 看成 disdis,观察发现 xx 要满足的不等式 xa≤xb+cx_a\le x_b+c与 disdis 中的 disto≤disnow+ai.wdis_{to}\le dis_{now}+a_i.w 相同。(这里 disdis 满足的条件不是更新的条件,而是全部更新完后任意 disdis 满足的条件)

然后看怎么连边。disto≤disnow+ai.wdis_{to}\le dis_{now}+a_i.w 中是 nownow 向 toto 连边,所以 xa≤xb+cx_a\le x_b+c 是 xbx_b 向 xax_a 连边,所以 xa−xb≤cx_a-x_b\le c 是 xbx_b 向 xax_a 连边,因此是反着连。

连完边不知道谁是源点,就设一个“超级源点”ss 表示 00。

怎么连边呢? ∀x,−∞≤x≤∞\forall x,-\infty\le x\le\infty,但不知道是连 −∞-\infty 还是 ∞\infty。考虑将 −∞≤x≤∞-\infty\le x\le\infty 变德和题目中的不等式一样,所以 x−0≤∞,0−x≤−∞x-0\le\infty,0-x\le-\infty。如果按照推出来的反向连边,用 ∞\infty 是 ss 向 xx 连边,是超级源点;而用 −∞-\infty 是 xx 向 00 连边,是超级终点。所以用 x−0≤∞x-0\le\infty。

C++
#include<bits/stdc++.h>
#define up(i,l,r) for(int i=l,END##i=r;i<=END##i;i++)
#define dn(i,r,l) for(int i=r,END##i=l;i>=END##i;i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
using namespace std;
const int INF=0x3f3f3f3f,N=5e3+7,M=1e4+7;
struct e {
	ll nxt,to,w;
} a[M];
bool f[N];
ll dis[N],cnt[N];
ll head[N],tot;
ll n,m,s;
void add(ll x,ll y,ll z) {
	a[++tot].to=y,a[tot].w=z,a[tot].nxt=head[x],head[x]=tot;
}
namespace sol {
	bool spfa() {
		queue<ll> q;
		q.push(s);
		dis[s]=0,cnt[s]=1;
		while(!q.empty()) {
			ll id=q.front();
			q.pop();
			f[id]=0;
			for(int i=head[id]; i; i=a[i].nxt) {
				ll to=a[i].to;
				if(dis[to]>dis[id]+a[i].w) {
					dis[to]=dis[id]+a[i].w;
					cnt[to]=cnt[id]+1;
					if(cnt[to]>n+1) return 1;//加了超级源点后是 n+1 个点
					if(!f[to])f[to]=1,q.push(to);
				}

			}
		}
		return 0;
	}
	void solve() {
		cin>>n>>m;
		up(i,0,n) dis[i]=INF;
		while(m--) {
			ll u,v,w;
			cin>>u>>v>>w;
			add(v,u,w);//u-v<=w
		}
		up(i,1,n) add(s,i,INF/2);//i-0<=INF/2,避免出错
		if(spfa()) cout<<"NO";
		else up(i,1,n) cout<<dis[i]<<' ';
	}
}
using namespace sol;
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(nullptr);
	solve();
	return 0;
}


原文