defquicksort(arr):iflen(arr)<=1:return arrpivot = 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 inrange(n):x =int(input())arr.append(x)
arr = quicksort(arr)for index,a inenumerate(arr):if index ==len(arr)-1:print(f'{a}')breakprint(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
defmatrix_chain_order(p):n =len(p)-1 m =[[0for x inrange(n +1)]for y inrange(n +1)]for L inrange(2, n +1):for i inrange(1, n - L +2):j = i + L -1m[i][j]=float('inf')for k inrange(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]= qreturn m[1][n]if __name__ =="__main__":n =int(input())dims =list(map(int,input().split()))print(matrix_chain_order(dims))
题目链接
点击打开链接
题目解法
考虑 d ( i j k ) d(ijk) d(ijk) 不好求 但我们可以转化 d ( i j k ) ∑ u ∣ i ∑ v ∣ j ∑ w ∣ k [ ( u , v ) 1 ] [ ( u , w ) 1 ] [ ( v , w ) 1 ] d(ijk)\sum\limits_{u|i}\sum\limits_{v|j}\sum\limits_{w|k}[(u,v)1][(u,w)1]…