Advertisement
Araf_12

dijkstra_using_priority_queue

Jun 24th, 2023
1,197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define endl '\n'
  4. #define ll long long
  5. #define mod 1000000007
  6. #define N 10000006
  7. #define all(x) (x).begin(),(x).end()
  8. #define LL_INF (1LL << 62)
  9. #define INF (1 << 30)
  10. #define SetBit(x, k) (x |= (1LL << k))
  11. #define ClearBit(x, k) (x &= ~(1LL << k))
  12. #define CheckBit(x, k) ((x>>k)&1)
  13. const int mx=2e6+12;
  14. ll fact[N];
  15. ll powerMod(ll a, ll b){
  16.     if(b==0) return 1;
  17.  
  18.     if(b%2==0){
  19.         ll x = powerMod(a, b/2);
  20.         return (x*x)%mod;
  21.     }
  22.     else {
  23.         ll x = powerMod(a, b/2);
  24.         return ((x*x)%mod * a)%mod;
  25.     }
  26.  
  27.     return 0;
  28. }
  29.  
  30. ll inverseMod(ll a){
  31.     return powerMod(a, mod-2);
  32. }
  33.  
  34. ll nCrMod(ll n, ll r){
  35.     if (r == 0)
  36.         return 1;
  37.     if (r > n)
  38.         return 0;
  39.    
  40.     return (fact[n] * inverseMod((fact[r] * fact[n - r]) % mod)) % mod;
  41. }
  42. void factorial(){
  43. fact[0] = 1;
  44.     for(int i = 1; i < N; i++){
  45.         fact[i] = (fact[i-1]*i)%mod;
  46. }}
  47.  
  48.  
  49. // Coding starts from here...
  50. vector<pair<int,ll>>adj[mx];
  51.  
  52.  
  53. int main()
  54. {
  55.   ios::sync_with_stdio(false);cin.tie(0);
  56.   int n,m;cin>>n>>m;
  57.   for(int i=1;i<=m;i++){
  58.     ll u,v,w;
  59.     cin>>u>>v>>w;
  60.     adj[u].push_back({v,w});
  61.     adj[v].push_back({u,w});
  62.   }
  63.  
  64.   ll dis[n+1];
  65.   for(int i=1;i<=n;i++)dis[i]=LL_INF;
  66.   int src=1;
  67.   dis[src]=0;
  68.  
  69.  
  70.   priority_queue<pair<ll,int>>pq;
  71.   pq.push({0,src});
  72.   while(!pq.empty()){
  73.     auto x=pq.top();
  74.     pq.pop();
  75.  
  76.     ll d=-x.first;
  77.     int nd=x.second;
  78.     if(dis[nd]<d)continue;
  79.    
  80.     for(auto u:adj[nd]){
  81.         int v=u.first;
  82.         ll w=u.second;
  83.         if(dis[v]>d+w){
  84.             dis[v]=d+w;
  85.             pq.push({-dis[v],v});
  86.         }
  87.     }
  88.   }
  89.  
  90.     for(int i=1;i<=n;i++)cout<<dis[i]<<" ";cout<<endl;
  91.  
  92.  
  93.  
  94.  
  95.   return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement