华为OD机试真题-路口最短时间问题【C++】

题目

假定街道是棋盘型的,每格距离相等,车辆通过每格街道需要时间均为 timePerRoad;街道的街口(交叉点)有交通灯,灯的周期T(=lights[row][col])各不相同;车辆可直行、左转和右转,其中直行和左转需要等相应T时间的交通灯才可通行,右转无需等待。
现给出 n*m 个街口的交通灯周期,以及起止街口的坐标,计算车辆经过两个街口的最短时间。
其中:
1)起点和终点的交通灯不计入时间,且可以任意方向经过街口
2)不可超出 n*m 个街口,不可跳跃,但边线也是道路(即 lights[0][0] -> lights[0][1] 是有效路径)

入口函数定义:
/**
* lights : n*m 个街口每个交通灯的周期,值范围[0,120],n和m的范围为[1,9]
* timePerRoad : 相邻两个街口之间街道的通过时间,范围为[0,600]
* rowStart : 起点的行号
* colStart : 起点的列号
* rowEnd : 终点的行号
* colEnd : 终点的列号
* return : lights[rowStart][colStart] 与 lights[rowEnd][colEnd] 两个街口之间的最短通行时间
*/
int calcTime(int[][] lights,int timePerRoad,int rowStart,int colStart,int rowEnd,int colEnd)

输入描述

第一行输入 n 和 m,以空格分隔

之后 n 行输入 lights矩阵,矩阵每行m个整数,以空格分隔

之后一行输入 timePerRoad

之后一行输入 rowStart colStart,以空格分隔

最后一行输入 rowEnd colEnd,以空格分隔

输出描述

lights[rowStart][colStart] 与 lights[rowEnd][colEnd] 两个街口之间的最短通行时间

用例

输入

3 3
1 2 3
4 5 6
7 8 9
60
0 0
2 2

输出

245

说明

行走路线为 (0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) 走了4格路,2个右转,1个左转,共耗时 60+0+60+5+60+0+60=245

以下是C++的非递归解法,递归虽然能解该题,但是实际项目过程中,好的编码规范一律不允许使用递归,因为它会带来非常多的不确定性隐患。 

#include <
### 华为OD中的增强版 `strstr` 函数 #### 题目描述 题目要求实现一个增强版本的 `strstr` 函数,其功能是在源字符串中查找第一个匹配的目标字符串,并返回目标字符串首次出现位置相对于源字符串起始位置的偏移量。如果未找到,则返回 `-1`。此函数支持带有通配符模式的模糊查询。 #### 解题思路 为了处理带通配符的模糊查询,在遍历过程中需考虑多种情况: - 当前字符完全匹配; - 使用通配符代替任意单个字符; - 处理连续多个通配符的情况; 对于每种编程语言的具体实现方式有所不同,下面分别给出 C++ 和 Python 的解决方案[^1]。 #### C++ 实现方案 ```cpp #include <iostream> #include <string> using namespace std; int enhancedStrstr(const string& haystack, const string& needle) { int m = haystack.size(), n = needle.size(); for (int i = 0; i <= m - n; ++i) { bool match = true; for (int j = 0; j < n && match; ++j) { if (!(haystack[i + j] == '?' || needle[j] == '?' || haystack[i + j] == needle[j])) { match = false; } } if (match) return i; } return -1; } // 主程序用于读取输入并调用上述方法打印结果 int main() { string s, p; cin >> s >> p; cout << enhancedStrstr(s, p); } ``` #### Python 实现方案 ```python def enhanced_strstr(haystack: str, needle: str) -> int: m, n = len(haystack), len(needle) for i in range(m - n + 1): matched = True for j in range(n): if not any([ haystack[i+j] == ch or needle[j] == '?' for ch in [haystack[i+j], '?'] ]): matched = False break if matched: return i return -1 if __name__ == "__main__": source_string = input().strip() pattern_string = input().strip() result = enhanced_strstr(source_string, pattern_string) print(result) ``` 在实际考环境中需要注意的是,华为 OD 采用 ACM 模式进行考核,因此考生不仅需要完成核心算法逻辑的设计与编码工作,还需要自行负责数据的输入/输出操作部分[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值