改写成python语言import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Main { private static final int N = 1000 + 10; private static int[] get_cost(){ int[] cost = new int[N]; boolean[] vis = new boolean[N]; for(int i=1;i<N;i++){ cost[i] = -1; vis[i] = false; } LinkedList<Integer> que = new LinkedList<>(); que.addLast(1); cost[1] = 0; vis[1] = true; while(!que.isEmpty()){ int cur = que.pollFirst(); for(int i=1;i<=cur;i++){ int nxt = cur + cur / i; if(nxt >= N){ continue; } if(vis[nxt]){ continue; } vis[nxt] = true; cost[nxt] = cost[cur] + 1; que.addLast(nxt); } } return cost; } public static void main(String[] args) { int[] cost = get_cost(); int[] b = new int[N]; int[] c = new int[N]; int[] w = new int[N]; int[] dp = new int[12 * N]; Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); while (T > 0) { int n = scanner.nextInt(); int k = scanner.nextInt(); for (int i = 1; i <= n; i++) { b[i] = scanner.nextInt(); } for (int i = 1; i <= n; i++) { c[i] = scanner.nextInt(); } for (int i = 1; i <= n; i++) { w[i] = cost[b[i]]; } int sum_w = 0; for (int i = 1; i <= n; i++) { sum_w += w[i]; } int sum_c = 0; for (int i = 1; i <= n; i++) { sum_c += c[i]; } if (k >= sum_w) { System.out.println(sum_c); } else { for (int i = 0; i <= k; i++) { dp[i] = 0; } for (int i = 1; i <= n; i++) { for (int j = k; j >= w[i]; j--) { int v = dp[j - w[i]] + c[i]; if (dp[j] < v) { dp[j] = v; } } } System.out.println(dp[k]); } T--; } } }
时间: 2024-03-17 18:46:02 浏览: 87
这是Java代码,可以使用Jython将其转换成Python代码,也可以手动将其改写成Python代码。以下是手动改写的Python代码:
```python
from collections import deque
N = 1010
def get_cost():
cost = [-1] * N
vis = [False] * N
que = deque([1])
cost[1] = 0
vis[1] = True
while que:
cur = que.popleft()
for i in range(1, cur+1):
nxt = cur + cur // i
if nxt >= N or vis[nxt]:
continue
vis[nxt] = True
cost[nxt] = cost[cur] + 1
que.append(nxt)
return cost
def main():
cost = get_cost()
dp = [0] * (12 * N)
T = int(input())
for _ in range(T):
n, k = map(int, input().split())
b = list(map(int, input().split()))
c = list(map(int, input().split()))
w = [cost[b[i]] for i in range(n)]
sum_w = sum(w)
sum_c = sum(c)
if k >= sum_w:
print(sum_c)
else:
for i in range(k+1):
dp[i] = 0
for i in range(n):
for j in range(k, w[i]-1, -1):
v = dp[j - w[i]] + c[i]
if dp[j] < v:
dp[j] = v
print(dp[k])
if __name__ == '__main__':
main()
```
阅读全文