#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
class DijkstraHeap {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int start, int end) { // N顶点数量,K起点
const int INF = 0x3f3f3f3f;
using PII = pair<int, int>; // first:距离; second: 几号点
vector<bool> vis(N+1, false); // 是否已得到最短距离
vector<int> dis(N+1, INF); // 距离起始点的最短距离
unordered_map<int, vector<PII>> graph; // 邻接表;u->v,权重w
priority_queue<PII, vector<PII>, greater<>> heap; // 小顶堆;维护到起始点的最短距离和点
for (auto &t: times){ // 初始化邻接表
graph[t[0]].push_back({t[2],t[1]});
}
heap.push({0, start});
dis[start] = 0;
vis[start] = true;
while(!heap.empty()){
auto t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if (vis[ver]) continue; // 之前更新过,是冗余备份
vis[ver] = true;
for (auto &p: graph[ver]){
if (dis[p.second] > distance + p.first){ // 用t去更新其他点到起始点的最短距离
dis[p.second] = distance + p.first;
if(end == p.second) return dis[end];
heap.push({dis[p.second], p.second});
}
}
}
// int ans = *max_element(dist.begin()+1, dist.end());
// return ans == INF ? -1: ans;
}
};
class spfaLinjiebiao {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int start, int end) {
const int INF = 0x3f3f3f3f;
vector<int> dis(N+1, INF); // 保存到起点的距离
vector<bool> vis(N+1, false); // 是否在队列中
typedef pair<int, int> PII;
unordered_map<int, vector<PII>> edges; // 邻接表
queue<int> q;
q.push(start);
dis[start] = 0;
vis[start] = true; // 是否在队列中
for (auto &t: times){
edges[t[0]].push_back({t[1], t[2]});
}
while (!q.empty()) { // 当没有点可以更新的时候,说明得到最短路
auto t = q.front();
q.pop();
vis[t] = false;
for (auto &e: edges[t]){ // 更新队列中的点出发的 所有边
int v = e.first, w = e.second;
if (dis[v] > dis[t] + w){
dis[v] = dis[t] + w;
if (!vis[v]){
q.push(v);
vis[v] = true;
}
}
}
}
return dis[end];
// int ans = *max_element(dist.begin()+1, dist.end());
// return ans == INF ? -1: ans;
}
};
class spfaLinjiejuzhen{
public:
int networkDelayTime(vector<vector<int>>& times, int N, int start, int end) {
const int INF = 0x3f3f3f3f;
int mp[N+1][N+1]; // 邻接矩阵
vector<bool> vis(N+1, false); // 是否已得到最短距离
vector<int> dis(N+1, INF); // 距离起始点的最短距离
dis[start] = 0;
vis[start] = true;
queue<int> q;
q.push(start);
while(!q.empty())
{
int now = q.front();
q.pop();
vis[now] = false;
for(int i=1; i<=N; i++)
if(dis[i] > dis[now]+mp[now][i])
{
dis[i] = dis[now]+mp[now][i];
if(!vis[i])
{
q.push(i);
vis[i] = true;
}
}
}
return dis[end];
}
};
07-29
4962
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)