网站首页 > 技术文章 正文
def min_distance():
# 读取输入
s = input().strip()
required = input().strip()
# 创建一个字典来存储每个字符的所有出现位置
from collections import defaultdict
char_positions = defaultdict(list)
for idx, char in enumerate(s):
char_positions[char].append(idx)
# 检查所有必过字符是否都存在
for char in required:
if char not in char_positions:
print(-1)
return
# 动态规划表,dp[i][j]表示处理到required的第i个字符时,位于s的第j个位置的最小总距离
# 初始化处理第一个字符的所有可能位置
dp = []
first_char = required[0]
for pos in char_positions[first_char]:
dp.append((pos, 0)) # (current position, total distance)
for i in range(1, len(required)):
current_char = required[i]
next_dp = []
for pos in char_positions[current_char]:
min_dist = float('inf')
for prev_pos, prev_dist in dp:
# 计算从prev_pos到pos的距离
dist = abs(pos - prev_pos)
if prev_dist + dist < min_dist:
min_dist = prev_dist + dist
next_dp.append((pos, min_dist))
dp = next_dp
# 找出所有可能位置中的最小总距离
if not dp:
print(-1)
else:
min_total = min(dist for pos, dist in dp)
print(min_total)
min_distance()
关键步骤:
- 字母位置记录:首先记录每个字母在字符串中的位置(索引),因为同一个字母可能出现多次。
- 必过点处理:处理必过的点,确定每个必过点的字母在字符串中的位置。
- 动态规划计算最小距离:使用动态规划来计算从一个必过点到下一个必过点的最小距离。动态规划的状态可以表示为当前所在的字母位置,以及已经经过的必过点数量。
猜你喜欢
- 2025-05-09 Python基础教程——列表(一)(python列表编程)
- 2025-05-09 Python学习笔记第一篇(2021年12月14日)——图像的位深度
- 2025-05-09 一文搞懂Python中的import与目录层级
- 2025-05-09 用Python写一个图算法之最短路径算法含注释说明
- 2025-05-09 Introduction to Python Lists 列表介绍
- 2025-05-09 Python 列表(List)详解(python列表讲解)
- 2025-05-09 详解Python 基础知识(python 基础 详细)
- 2025-05-09 python海龟绘图turtle(一):画布和窗体
- 2025-05-09 Python使用bokeh及folium实现地理位置信息的交互可视化
- 2025-05-09 Python高手进阶:深入os.path模块高效处理路径问题
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 252℃Python实现字符串小写转大写并写入文件
- 108℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)