单源最短路:Dijksra
单源最短路,时间复杂度\(O(nlog(n+m))\)
不适用于有负权边的图
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct edge
{
int to, w;
};
vector<vector<edge>> adj;
vector<int> dis;
vector<bool> vis;
int n, m, start;
bool operator<(const edge a, const edge b) // 大根堆:重载小于号
{
return a.w > b.w;
}
bool cmp(const edge a, const edge b)
{
return a.w > b.w;
}
void dijkstra(int start)
{
dis[start] = 0;
priority_queue<edge> pq;
pq.push({start, 0});
while (!pq.empty())
{
auto [u, now] = pq.top();
pq.pop();
if (vis[u])
continue;
vis[u] = 1;
for (auto [to, w] : adj[u])
{
if (!vis[to] and dis[u] + w < dis[to])
{
dis[to] = dis[u] + w;
pq.push({to, dis[to]});
}
}
}
}
void add(int a, int b, int w)
{
adj[a].push_back({b, w});
}
int main()
{
cin >> n >> m >> start;
dis.resize(n + 1, INT_MAX);
vis.resize(n + 1, 0);
adj.resize(n + 1);
for (int i = 0; i < m; ++i)
{
int a, b, w;
cin >> a >> b >> w;
add(a, b, w);
}
dijkstra(start);
for (int i = 1; i <= n; ++i)
cout << dis[i] << ' ';
cout << '\n';
return 0;
}
标签:pq,vis,int,Dijksra,单源,start,模板,dis
From: https://www.cnblogs.com/2hard4me/p/18597658