1 介绍
本博客用来记录使用dijkstra算法或spfa算法求解最短路问题的题目。
2 训练
题目1:1129热浪
C++代码如下,
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 2510;
int n, m;
vector<vector<pair<int,int>>> g; //first表示next_node,second表示w
int dist[N];
bool st[N];
int snode, enode;
void dijkstra() {
memset(dist, 0x3f, sizeof dist);
dist[snode] = 0;
priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int,int>>> h;
h.push(make_pair(0, snode));
while (!h.empty()) {
//确定当前结点中,不在集合s且距离结点snode最近的结点。记作cnode
auto t = h.top();
h.pop();
int cdist = t.first, cnode = t.second;
if (st[cnode]) continue; //如果cnode已经被确定是最小路径上的结点了,则跳过
st[cnode] = true; //将它加入到集合中
for (auto [next_node, w] : g[cnode]) {
if (dist[next_node] > cdist + w) {
dist[next_node] = cdist + w;
h.push(make_pair(dist[next_node], next_node));
}
}
}
return;
}
int main() {
cin >> n >> m >> snode >> enode;
g.resize(n + 10);
for (int i = 1; i <= m; ++i) {
int a, b, c;
cin >> a >> b >> c;
g[a].emplace_back(b, c);
g[b].emplace_back(a, c);
}
//求snode到enode的最短距离
dijkstra();
cout << dist[enode] << endl;
return 0;
}
题目2:1128信使
C++代码如下,
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 110;
int n, m;
int d[N];
bool st[N];
vector<vector<pair<int,int>>> g;
void dijkstra() {
memset(d, 0x3f, sizeof d);
d[1] = 0;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater