题目地址:
https://www.luogu.com.cn/problem/P1339
题目描述:
有一个
n
n
n个点
m
m
m条边的无向图,请求出从
s
s
s到
t
t
t的最短路长度。
输入格式:
第一行四个正整数
n
,
m
,
s
,
t
n,m,s,t
n,m,s,t。 接下来
m
m
m行,每行三个正整数
u
,
v
,
w
u,v,w
u,v,w,表示一条连接
u
,
v
u,v
u,v,长为
w
w
w的边。
输出格式:
输出一行一个整数,表示答案。
数据范围:
对于
100
%
100\%
100%的数据,
1
≤
n
≤
2500
1\le n \le 2500
1≤n≤2500,
1
≤
m
≤
6200
1\le m \le 6200
1≤m≤6200,
1
≤
w
≤
1000
1\le w \le 1000
1≤w≤1000。
直接用Dijkstra算法。可以看出是稀疏图,所以用堆优化版本。代码如下:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
using PII = pair<int, int>;
// 注意边要开两倍
const int N = 2510, M = 6200 * 2 + 10;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
int s, ed;
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int main() {
scanf("%d%d%d%d", &n, &m, &s, &ed);
memset(h, -1, sizeof h);
memset(dist, 0x3f, sizeof dist);
while (m--) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
priority_queue<PII, vector<PII>, greater<>> heap;
dist[s] = 0;
heap.push({0, s});
while (heap.size()) {
auto t = heap.top(); heap.pop();
int v = t.second, d = t.first;
if (v == ed) {
printf("%d\n", d);
break;
}
if (st[v]) continue;
st[v] = true;
for (int i = h[v]; ~i; i = ne[i]) {
int j = e[i];
if (!st[j] && dist[j] > dist[v] + w[i]) {
dist[j] = dist[v] + w[i];
heap.push({dist[j], j});
}
}
}
return 0;
}
时间复杂度 O ( m log n ) O(m\log n) O(mlogn),空间 O ( n ) O(n) O(n)。