题解 | #【模板】单源最短路1#
【模板】单源最短路1
https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8
#include <iostream> #include <cstring> #include <queue> using namespace std; typedef long long LL; const int N = 5050; struct edge{int v,w;}; vector <edge> e[N]; priority_queue <pair<LL,LL>> q; bool vis[N]; LL d[N]; int n,m; void dijkstra(int s){ memset(d,-1,sizeof d); d[s]=0; q.push({0,s}); while(q.size()){ auto t = q.top(); q.pop(); int u =t.second; if(vis[u]) continue; vis[u]= true; for(auto ed:e[u]){ LL v=ed.v,w=ed.w; if(d[v]>d[u]+w||d[v]==-1){ d[v] =d[u]+w; q.push({-d[v],v}); } } } } int main(){ cin>>n>>m; while(m--){ int a,b; if(a>n||b>n) continue; cin>>a>>b; e[a].push_back({b,1}); e[b].push_back({a,1}); } dijkstra(n); //无向图 cout<<d[1]<<endl; return 0; }