酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

给定n个互异的关键字组成的序列k=<k1,k2,...,kn>,且关键字有序(k1<k2<...<kn),从这些关键字中构造一棵二叉查找树。对每个关键字ki,每次搜索到的概率为pi。还有n+1个“虚拟键”d0,d1,...,dn,他们代表不在k的值。d0代表所有小于k1的值,dn代表所有大于kn的值,对于i = 1,2,...,n-1,虚拟键di代表位于ki和ki+1之间的值。对于每个di,每次搜索di的概率为qi。要求建立一棵最优二叉查找树,使所有的搜索操作访问的结点总数最少,并输出平均搜索每个结点的访问结点数的值。 输入描述 第一行n个实数p1,p2...pn, 表示k1,k2,...kn搜索到的概率。 第二行n+1个实数d0,d1,...dn, 表示 n+1个虚拟键搜索到的概率。 输出描述 一个实数,表示平均搜索每个结点的访问结点数的值。 输入样例 0.15 0.1 0.05 0.1 0.2 0.05 0.1 0.05 0.05 0.05 0.1 输出样例 一个实数,保留两位小数结果值。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) ``` 运行以上代码可以用于输入样例,输出样例中的测试数据。 [2024-06-09 19:52:43 | AI写代码神器 | 916点数解答]

相关提问