单源最短路径 模板(Dijkstra)
P4779 【模板】单源最短路径(标准版)
题目链接:https://www.luogu.com.cn/problem/P4779
P3371 【模板】单源最短路径(弱化版)
题目链接:
https://www.luogu.com.cn/problem/P3371
Dijkstra
#include <bits/stdc++.h>
using namespace std;
const int N=3e5+10;
typedef long long ll;
int n,m,s;
bool vis[N];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m>>s;
memset(vis,false,sizeof(vis));
vector<vector<pair<int,ll>>>graph(n+1);
vector<ll>dis(n+1,INT_MAX);
for(int i=0;i<m;i++)
{
int u,v,w;
cin>>u>>v>>w;
graph[u].push_back({v,w});
}
dis[s]=0;
priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<pair<ll,int>>>pq;
pq.push({0,s});
while(!pq.empty())
{
pair<ll,int>node = pq.top();
pq.pop();
int u = node.second;
if(vis[u])continue;
vis[u]=true;
for(auto it:graph[u])
{
int v = it.first;
int w = it.second;
if(!vis[v]&&dis[u]+w<=dis[v])
{
dis[v]=dis[u]+w;
pq.push({dis[v],v});
}
}
}
for(int i=1;i<=n;i++)cout<<dis[i]<<' ';
cout<<endl;
return 0;
}

浙公网安备 33010602011771号