Skip to content

Commit a427f76

Browse files
authored
Create minimum-score-of-a-path-between-two-cities.cpp
1 parent 1d2f957 commit a427f76

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(n + m), m = len(roads)
2+
// Space: O(n + m)
3+
4+
// bfs
5+
class Solution {
6+
public:
7+
int minScore(int n, vector<vector<int>>& roads) {
8+
vector<vector<pair<int, int>>> adj(n);
9+
for (const auto& r : roads) {
10+
adj[r[0] - 1].emplace_back(r[1] - 1, r[2]);
11+
adj[r[1] - 1].emplace_back(r[0] - 1, r[2]);
12+
}
13+
const auto& bfs = [&]() {
14+
vector<bool> lookup(size(adj));
15+
vector<int> q = {0};
16+
lookup[0] = true;
17+
while (!empty(q)) {
18+
vector<int> new_q;
19+
for (const auto& u : q) {
20+
for (const auto& [v, w] : adj[u]) {
21+
if (lookup[v]) {
22+
continue;
23+
}
24+
lookup[v] = true;
25+
new_q.emplace_back(v);
26+
}
27+
}
28+
q = move(new_q);
29+
}
30+
return lookup;
31+
};
32+
33+
const auto& lookup = bfs();
34+
int result = numeric_limits<int>::max();
35+
for (const auto& r : roads) {
36+
if (lookup[r[0] - 1]) {
37+
result = min(result, r[2]);
38+
}
39+
}
40+
return result;
41+
}
42+
};

0 commit comments

Comments
 (0)