-
Notifications
You must be signed in to change notification settings - Fork 177
/
Network_delay_time.cpp
67 lines (53 loc) · 1.67 KB
/
Network_delay_time.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <utility>
#include <limits.h>
using namespace std;
class Solution {
public:
vector<pair<int, int>> G[6001];
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<int> visited(n + 1, INT_MAX); // Initialize distances with INT_MAX
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> PQ; // Min-heap
// Build the graph
for(int i = 0; i < times.size(); i++) {
G[times[i][0]].push_back({times[i][2], times[i][1]});
}
// Initialize starting point
PQ.push({0, k});
visited[k] = 0;
while(!PQ.empty()) {
pair<int, int> u = PQ.top();
PQ.pop();
int uCost = u.first;
int uNode = u.second;
if(uCost > visited[uNode]) continue;
for(pair<int, int> v : G[uNode]) {
int vCost = v.first;
int vNode = v.second;
int newDist = uCost + vCost;
if(newDist < visited[vNode]) {
visited[vNode] = newDist;
PQ.push({newDist, vNode});
}
}
}
int ans = 0;
for(int i = 1; i <= n; i++) {
if(visited[i] == INT_MAX) return -1;
ans = max(ans, visited[i]);
}
return ans;
}
};
int main() {
Solution solution;
vector<vector<int>> times = {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}};
int n = 4;
int k = 2;
int result = solution.networkDelayTime(times, n, k);
cout << "Network delay time: " << result << endl;
return 0;
}