1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
the-most-similar-path-in-a-graph.cpp 1.37 KB
一键复制 编辑 原始数据 按行查看 历史
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助