[Hacker Rank] Jack goes to Rapture

Jack goes to Rapture

  • Time : O(v + e)
  • Space : O(v + e)
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

void getCost(int n, vector<int> f, vector<int> t, vector<int> w) {
vector<int> vis(n + 1, INT_MAX);
vis[1] = 0;
vector<pair<int, int>> adj[n + 1];
for(int i = 0; i < w.size(); i++) {
int u = f[i], v = t[i], c = w[i];
adj[u].push_back({v, c});
adj[v].push_back({u, c});
}
queue<int> q;
vector<int> inc(n + 1, 0);
q.push(1);
while(!q.empty()) {
auto u = q.front(); q.pop();
inc[u] = false;
for(auto& [v, c] : adj[u]) {
if(vis[v] > max(vis[u], c)) {
vis[v] = max(vis[u], c);
if(!inc[v]) {
inc[v] = true;
q.push(v);
}
}
}
}

if(vis[n] != INT_MAX)
cout<< vis[n] << '\n';
else
cout<< "NO PATH EXISTS" << '\n';
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/09/PS/HackerRank/jack-goes-to-rapture/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.