def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
# 测试代码
n = int(input())
arr = []
for i in range(n):
x = int(input())
arr.append(x)
arr = quicksort(arr)
for index,a in enumerate(arr):
if index == len(arr) - 1:
print(f'{a}')
break
print(f'{a}', end=' ')
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N];
int v[N], w[N];
int n, m;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> m >> n;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i++) {
for (int j = m; j >= v[i]; j--) {
f[j] = max(f[j], f[j - v[i]] + w[i]);
}
}
cout << f[m] << endl;
}
7-11 python
python复制代码
def matrix_chain_order(p):
n = len(p) - 1
m = [[0 for x in range(n + 1)] for y in range(n + 1)]
for L in range(2, n + 1):
for i in range(1, n - L + 2):
j = i + L - 1
m[i][j] = float('inf')
for k in range(i, j):
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]
if q < m[i][j]:
m[i][j] = q
return m[1][n]
if __name__ == "__main__":
n = int(input())
dims = list(map(int, input().split()))
print(matrix_chain_order(dims))