Advertisement
Falak_Ahmed_Shakib

Dijkstra - Single Source Shortest Path

Aug 30th, 2021
972
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. //pb : https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_B#
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. typedef long long  ll;
  5. typedef pair<ll,ll> pll;
  6. #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL))
  7. #define fi first
  8. #define se second
  9. #define pb push_back
  10. ll const MOD=1000000007;
  11.  
  12. const int M=100005;
  13.  
  14. #define eb emplace_back
  15.  
  16. vector<pll>adj[M+10];
  17.  
  18. ll n,m;
  19.  
  20.  
  21. ll cost[M+1];
  22.  
  23.  
  24. void Dijkstra(ll s)
  25. {
  26.  
  27.  
  28.    priority_queue<pll,vector<pll>,greater<pll>>q;
  29.  
  30.  
  31.    for(ll i=0;i<=M;i++)
  32.    {
  33.        cost[i]=1e8;
  34.    }
  35.  
  36.    q.push({0,s});
  37.     cost[s]=0;
  38.  
  39.    while(!q.empty())
  40.    {
  41.          ll u=q.top().se;
  42.           q.pop();
  43.  
  44.           for(auto x:adj[u])
  45.           {
  46.               ll v=x.fi;
  47.               ll w=x.se;
  48.  
  49.               if(cost[u]+w<cost[v])
  50.               {
  51.                   cost[v]=cost[u]+w;
  52.                   q.push({cost[v],v});
  53.               }
  54.  
  55.  
  56.           }
  57.    }
  58.  
  59.  
  60. }
  61. void input()
  62. {
  63.      cin>>n;
  64.  
  65.     ll a,b,w;
  66.  
  67.     for(ll i=1;i<=n;i++)
  68.     {
  69.         ll k;
  70.  
  71.        cin>>a>>k;
  72.  
  73.        while(k--)
  74.        {
  75.            cin>>b>>w;
  76.  
  77.              adj[a].eb(b,w);
  78.  
  79.       // v[b].eb(a,w);
  80.        }
  81.  
  82.  
  83.     }
  84. }
  85. int main()
  86. {
  87.     fastread();
  88.  
  89.     input();
  90.  
  91.    //fill(cost,cost+n+2,1e9);
  92.  
  93.     Dijkstra(0);
  94.  
  95.     for(ll i=0; i<n; i++)
  96.     {
  97.         cout<<i<<" "<<cost[i]<<endl;
  98.     }
  99.  
  100.  
  101.  
  102.  
  103.  
  104. }
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement