forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-most-similar-path-in-a-graph.cpp
37 lines (34 loc) · 1.37 KB
/
the-most-similar-path-in-a-graph.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
// Time: O(n^2 * m), m is the length of targetPath
// Space: O(n * m)
class Solution {
public:
vector<int> mostSimilar(int n, vector<vector<int>>& roads, vector<string>& names, vector<string>& targetPath) {
vector<vector<int>> adj(n);
for (const auto& road : roads) {
adj[road[0]].emplace_back(road[1]);
adj[road[1]].emplace_back(road[0]);
}
vector<vector<int>> dp(targetPath.size() + 1, vector<int>(n));
for (int i = 1; i <= targetPath.size(); ++i) {
for (int v = 0; v < n; ++v) {
dp[i][v] = targetPath.size();
for (const auto& u : adj[v]) {
dp[i][v] = min(dp[i][v], dp[i - 1][u]);
}
dp[i][v] += int(names[v] != targetPath[i - 1]);
}
}
vector<int> path = {static_cast<int>(distance(cbegin(dp.back()),
min_element(cbegin(dp.back()), cend(dp.back()))))};
for (int i = targetPath.size(); i >= 2; --i) {
for (const auto& u : adj[path.back()]) {
if (dp[i - 1][u] + int(names[path.back()] != targetPath[i - 1]) == dp[i][path.back()]) {
path.emplace_back(u);
break;
}
}
}
reverse(begin(path), end(path));
return path;
}
};