Python实现:从互异关键字序列构造最优二叉查找树并求平均搜索结点数
```python import sys n_values = list(map(float, sys.stdin.readline().split())) d_values = list(map(float, sys.stdin.readline().split())) n = len(n_values) # Create a matrix to store the optimal costs cost_matrix = [[0] * (n + 1) for _ in range(n + 1)] # Create a matrix to store the probabilities prob_matrix = [[0] * (n + 1) for _ in range(n + 1)] # Calculate the cumulative probabilities for real keys cumulative_p = [0] * (n + 1) for i in range(1, n + 1): cumulative_p[i] = cumulative_p[i - 1] + n_values[i - 1] # Calculate the cumulative probabilities for dummy keys cumulative_q = [0] * (n + 1) for i in range(1, n + 1): cumulative_q[i] = cumulative_q[i - 1] + d_values[i - 1] # Dynamic programming approach to calculate the optimal cost matrix for l in range(1, n + 1): for i in range(0, n - l + 1): j = i + l prob_matrix[i][j] = cumulative_p[j] - cumulative_p[i] + cumulative_q[j] - cumulative_q[i] cost_matrix[i][j] = sys.maxsize for r in range(i, j): cost = cost_matrix[i][r] + cost_matrix[r + 1][j] + prob_matrix[i][j] if cost < cost_matrix[i][j]: cost_matrix[i][j] = cost # Print the average number of visits to nodes average_visits = round(cost_matrix[0][n], 2) print(average_visits) ``` 运行以上代码可以用于输入样例,输出样例中的测试数据。 ######[AI写代码神器 | 916点数解答 | 2024-06-09 19:52:43]
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)460
- 求解特定条件下整数序列的最小值:算法分析与代码实现(字节豆包 | 746点数解答 | 2026-01-24 13:14:40)55
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)345
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)416
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)408
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)313
- iOS开发:weak关键字使用场景及与assign的差异揭秘(阿里通义 | 311点数解答 | 2023-11-08 00:37:04)276
- iOS开发全解析:“copy”关键字的使用方法与实例演示(阿里通义 | 272点数解答 | 2023-11-08 00:37:13)308
- iOS开发:@property声明NSString等用copy而非strong的原因及改strong的后果(阿里通义 | 278点数解答 | 2023-11-08 00:37:19)441
- iOS开发:Objective - C中weak与assign关键字的使用场景及差异揭秘(百度文心 | 360点数解答 | 2023-11-09 17:38:45)351
- Java调用Python接口中文乱码?设置UTF - 8编码一招解决!(讯飞星火 | 263点数解答 | 2024-06-06 17:07:59)391
- 解决Java调用Python接口中文乱码问题:设置UTF - 8编码全攻略(讯飞星火 | 160点数解答 | 2024-06-06 17:18:39)416