Loading [MathJax]/jax/input/TeX/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >LeetCode 1548. The Most Similar Path in a Graph(动态规划)

LeetCode 1548. The Most Similar Path in a Graph(动态规划)

作者头像
Michael阿明
发布于 2021-02-19 03:13:08
发布于 2021-02-19 03:13:08
1.2K00
代码可运行
举报
运行总次数:0
代码可运行

文章目录

1. 题目

We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai with city bi. Each city has a name consisting of exactly 3 upper-case English letters given in the string array names. Starting at any city x, you can reach any city y where y != x (i.e. the cities and the roads are forming an undirected connected graph).

You will be given a string array targetPath. You should find a path in the graph of the same length and with the minimum edit distance to targetPath.

You need to return the order of the nodes in the path with the minimum edit distance, The path should be of the same length of targetPath and should be valid (i.e. there should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers return any one of them.

The edit distance is defined as follows:

Follow-up: If each node can be visited only once in the path, What should you change in your solution?

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: n = 5, 
roads = [[0,2],[0,3],[1,2],[1,3],[1,4],[2,4]], 
names = ["ATL","PEK","LAX","DXB","HND"], 
targetPath = ["ATL","DXB","HND","LAX"]
Output: [0,2,4,2]
Explanation: [0,2,4,2], [0,3,0,2] and [0,3,1,2] are accepted answers.
[0,2,4,2] is equivalent to ["ATL","LAX","HND","LAX"] which has edit distance = 1 with targetPath.
[0,3,0,2] is equivalent to ["ATL","DXB","ATL","LAX"] which has edit distance = 1 with targetPath.
[0,3,1,2] is equivalent to ["ATL","DXB","PEK","LAX"] which has edit distance = 1 with targetPath.

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: n = 4, 
roads = [[1,0],[2,0],[3,0],[2,1],[3,1],[3,2]], 
names = ["ATL","PEK","LAX","DXB"], 
targetPath = ["ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX"]
Output: [0,1,0,1,0,1,0,1]
Explanation: Any path in this graph has edit distance = 8 with targetPath.

Example 3:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: n = 6, 
roads = [[0,1],[1,2],[2,3],[3,4],[4,5]], 
names = ["ATL","PEK","LAX","ATL","DXB","HND"], 
targetPath = ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
Output: [3,4,5,4,3,2,1]
Explanation: [3,4,5,4,3,2,1] is the only path with edit distance = 0 with targetPath.
It's equivalent to ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
 
Constraints:
2 <= n <= 100
m == roads.length
n - 1 <= m <= (n * (n - 1) / 2)
0 <= ai, bi <= n - 1
ai != bi 
The graph is guaranteed to be connected and each pair of nodes may have at most one direct road.
names.length == n
names[i].length == 3
names[i] consists of upper-case English letters.
1 <= targetPath.length <= 100
targetPath[i].length == 3
targetPath[i] consists of upper-case English letters.

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/the-most-similar-path-in-a-graph 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    vector<int> mostSimilar(int n, vector<vector<int>>& roads, vector<string>& names, vector<string>& targetPath) {
        vector<vector<int>> g(n);
        for(auto& r : roads)
        {
            g[r[0]].push_back(r[1]);
            g[r[1]].push_back(r[0]);
        }//建图
        int len = targetPath.size();
        vector<vector<int>> dp(len, vector<int>(n, INT_MAX));
        //走完 ?target后的 在城市 ni 的最小编辑距离
        vector<vector<int>> path1(n);//n个城市作为结束的最佳路线
        vector<vector<int>> path2(n);//存储下一个状态的路径
        for(int i = 0; i < n; ++i)//初始化
        {
            dp[0][i] = (names[i] != targetPath[0]);
            path1[i].push_back(i);
        }
        int mindis = INT_MAX, minidx = -1;
        for(int k = 1;  k < len; ++k)
        {	//样本维度
            for(int i = 0; i < n; ++i)
            {	//前一个城市
                if(dp[k-1][i] == INT_MAX)
                    continue;
                for(int j : g[i])
                {	//下一个相连的城市
                    if(dp[k][j] > dp[k-1][i]+(names[j]!=targetPath[k]))
                    {
                        dp[k][j] = dp[k-1][i]+(names[j]!=targetPath[k]);
                        path2[j] = path1[i];
                        path2[j].push_back(j);
                    }
                }
            }
            swap(path1, path2);//滚动数组,更新当前的最佳路径至path1
        }
        for(int i = 0; i < n; i++) 
        {
            if(mindis > dp[len-1][i])
            {
                mindis = dp[len-1][i];
                minidx = i;
            }
        }//取编辑距离最小的城市编号
        return path1[minidx];//返回路径
    }
};

1260 ms 109.6 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/08/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
LeetCode 1320. 二指输入的的最小距离(动态规划)
二指输入法定制键盘在 XY 平面上的布局如上图所示,其中每个大写英文字母都位于某个坐标处, 例如字母 A 位于坐标 (0,0),字母 B 位于坐标 (0,1),字母 P 位于坐标 (2,3) 且字母 Z 位于坐标 (4,1)。
Michael阿明
2021/02/19
5140
LeetCode 1320. 二指输入的的最小距离(动态规划)
leetcode刷题记录——动态规划
首先找到数组 nums 中的最大元素值 maxNum。然后创建一个长度为 maxNum + 1 的数组 dp,用于记录删除元素值的获得的分数。
Andromeda
2023/12/25
2050
LeetCode 241. 为运算表达式设计优先级(动态规划)
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。 你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
Michael阿明
2020/07/13
7200
LeetCode 241. 为运算表达式设计优先级(动态规划)
HOJ-1005 Fast Food(动态规划)
Fast Food My Tags (Edit) Source : Unknown Time limit : 3 sec Memory limit : 32 M Submitted : 3777, Accepted : 1147 The fastfood chain McBurger owns several restaurants along a highway. Recently, they have decided to build several depots al
ShenduCC
2018/04/26
5700
周赛选讲:图论,字符串,动态规划
知识点:图论,动态规划,字符串,状态压缩 规定时间内到达终点的最小花费 image.png 题解 image.png class Solution { public: #define pb push_back #define pii pair<int, int> #define fi first #define se second #define INF 0x3f3f3f3f const int N = 1e3 + 7; int minCost(i
ACM算法日常
2021/07/16
3410
挑战程序竞赛系列(29):3.4熟练掌握动态规划
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014688145/article/details/76117385
用户1147447
2019/05/26
5250
动态规划-树形DP
树形DP,顾名思义是在「树」这种数据结构上进行的DP,往往给定一棵树,通过指定操作求最小代价或最大收益等。 一般方向主要分①从子节点向根节点传递信息,②根节点向子节点传递 树操作一般利用递归和搜索,如树的遍历等,用dfs编程会比较简单,但往往状态转移方程不好设计,常常比较难(主要是我太菜了 ),令人头秃。做题步骤一般是:建树、树的遍历、DP。
唔仄lo咚锵
2020/09/15
1.1K0
LeetCode 第 210 场周赛 解题报告
那么在遍历过程中,栈中元素数量的最大值即为答案。栈中的(可以理解为还没遍历到匹配的),即那些嵌套的(。
ACM算法日常
2020/10/30
5070
LeetCode 第 210 场周赛 解题报告
PAT 1003 Emergency (25分) Dijstra
As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.
vivi
2020/07/14
3770
LeetCode 0064 - Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Reck Zhang
2021/08/11
2210
PAT 1018 Public Bike Management(Dijkstra 最短路)
1018. Public Bike Management (30) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue There is a public bike service in Hangzhou City which provides great convenience to the tourists from all over the world. One may rent
ShenduCC
2018/04/26
7800
PAT 1018 Public Bike Management(Dijkstra 最短路)
HOJ 2133&POJ 2964 Tourist(动态规划)
Tourist Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1503 Accepted: 617 Description A lazy tourist wants to visit as many interesting locations in a city as possible without going one step further than necessary. Starting from
ShenduCC
2018/04/26
7040
年会Party(树形动态规划)- HDU 1520
There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests' conviviality ratings.
ACM算法日常
2018/08/07
6240
hdu----(2586)How far away ?(DFS/LCA/RMQ)
How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 5492    Accepted Submission(s): 2090 Problem Description There are n houses in the village and some bidirectional roads connecting
Gxjun
2018/03/26
5730
CodeForces 666B World Tour(spfa+枚举)
B. World Tour time limit per test 5 seconds memory limit per test 512 megabytes input standard input output standard output A famous sculptor Cicasso goes to a world tour! Well, it is not actually a world-wide. But not everyone should have th
ShenduCC
2018/04/26
5870
CodeForces 666B World Tour(spfa+枚举)
【动态规划算法练习】day9
647. 回文子串 给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。 回文字符串 是正着读和倒过来读一样的字符串。 子字符串 是字符串中的由连续字符组成的一个序列。 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
摘星
2023/10/15
1460
【动态规划算法练习】day9
LeetCode 879. 盈利计划(动态规划)
第 i 种工作会产生 profit[i] 的利润,它要求 group[i] 名成员共同参与。如果成员参与了其中一项工作,就不能参与另一项工作。
Michael阿明
2021/09/06
2530
LeetCode 1547. Minimum Cost to Cut a Stick(动态规划)
dp[i][j] = min { dp[i][k-1] + cost(k) + dp[k+1][j]} i<=k<=j
ShenduCC
2020/08/19
6330
uva 11324 The Largest Clique(图论-tarjan,动态规划)
Given a directed graph G, consider the following transformation. First, create a new graph T(G) to have the same vertex set as G. Create a directed edge between two vertices u and v in T(G) if and only if there is a path between u and v in G that follows the directed edges only in the forward direction. This graph T(G) is often called the transitive closure of G.
全栈程序员站长
2022/07/06
1850
LeetCode 周赛上分之旅 #48 一道简单的树上动态规划问题
元素的集合,根据题意逆向遍历数组并从集合中移除元素,当集合为空时表示已经收集到所有元素,返回
用户9995743
2023/10/04
3080
LeetCode 周赛上分之旅 #48 一道简单的树上动态规划问题
相关推荐
LeetCode 1320. 二指输入的的最小距离(动态规划)
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验