-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2045.SecondMinimumTimeToReachDestination.cpp
More file actions
54 lines (45 loc) · 1.46 KB
/
2045.SecondMinimumTimeToReachDestination.cpp
File metadata and controls
54 lines (45 loc) · 1.46 KB
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
class Solution {
public:
int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Map out graph.
unordered_map<int, list<int>> graph;
for (const vector<int>& edge : edges) {
const int u = edge[0], v = edge[1];
graph[u].push_back(v);
graph[v].push_back(u);
}
// Calculation variables.
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> queue;
vector<int> uniqueVisits(n + 1, 0);
vector<int> minimumNodeTime(n + 1, -1);
// Dijkstra's algorithm time.
// (Time, Node).
queue.push({ 0, 1 });
while (!queue.empty()) {
// Get highest priority node.
auto [nodeTime, nodeIndex] = queue.top();
queue.pop();
// Skip if already visited or past second minimum.
if (minimumNodeTime[nodeIndex] == nodeTime || uniqueVisits[nodeIndex] >= 2)
continue;
// Update tracking variables.
uniqueVisits[nodeIndex]++;
minimumNodeTime[nodeIndex] = nodeTime;
// Second minimum found.
if (nodeIndex == n && uniqueVisits[nodeIndex] == 2)
return minimumNodeTime[nodeIndex];
// Calculate the leaving time (waiting for the green light)
if ((nodeTime / change) % 2 != 0)
nodeTime = (nodeTime / change + 1) * change;
// Calculate neighbours next.
for (int neighbour : graph[nodeIndex])
queue.push({ nodeTime + time, neighbour });
}
// No second minimum found.
return -1;
}
};