Advertisement
nikunjsoni

743

May 28th, 2021
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     typedef pair<int, int> T;
  4.     int networkDelayTime(vector<vector<int>>& times, int n, int k) {
  5.         vector<vector<T>> graph(n+1);
  6.         for(auto edge:times){
  7.             graph[edge[0]].push_back({edge[1], edge[2]});
  8.         }
  9.        
  10.         vector<int> dist(n+1, INT_MAX);
  11.         priority_queue<T, vector<T>, greater<>> pq;
  12.         dist[k] = 0;
  13.         pq.push({dist[k], k});
  14.        
  15.         while(!pq.empty()){
  16.             auto node = pq.top(); pq.pop();
  17.             if(dist[node.second] < node.first) continue;
  18.             for(auto edge: graph[node.second]){
  19.                 if(dist[edge.first] > node.first+edge.second){
  20.                     dist[edge.first] = node.first+edge.second;
  21.                     pq.push({dist[edge.first], edge.first});
  22.                 }
  23.             }
  24.         }
  25.         int ans = 0;
  26.         for(int i=1; i<=n; i++)
  27.             ans = max(ans, dist[i]);
  28.         if(ans == INT_MAX) ans = -1;
  29.         return ans;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement