2040. 【模板】01背包

C++

#include <iostream> #include <vector> #include <algorithm> using namespace std; int knapsack(int N, int c, vector<int>& W, vector<int>& V) { vector<int> dp(c + 1, 0); for (int i = 1; i <= N; ++i) { for (int j = c; j >= W[i-1]; --j) { dp[j] = max(dp[j], dp[j - W[i-1]] + V[i-1]); } } return dp[c]; } int main() { int N, c; cin >> N >> c; vector<int> W(N), V(N); for (int i = 0; i < N; ++i) { cin >> W[i]; } for (int i = 0; i < N; ++i) { cin >> V[i]; } cout << knapsack(N, c, W, V) << endl; return 0; }

Python:

def knapsack(N, c, W, V): dp = [0] * (c + 1) for i in range(1, N + 1): for j in range(c, W[i-1]-1, -1): dp[j] = max(dp[j], dp[j - W[i-1]] + V[i-1]) return dp[c] N, c = map(int, input().split()) W = list(map(int, input().split())) V = list(map(int, input().split())) print(knapsack(N, c, W, V))

Java:

import java.util.Scanner; public class Main { public static long knapsack(int N, int c, long[] W, long[] V) { long[] dp = new long[c + 1]; for (int i = 1; i <= N; i++) { for (int j = c; j >= W[i-1]; j--) { dp[j] = Math.max(dp[j], dp[j - (int)W[i-1]] + V[i-1]); } } return dp[c]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int c = scanner.nextInt(); long[] W = new long[N]; long[] V = new long[N]; for (int i = 0; i < N; i++) { W[i] = scanner.nextLong(); } for (int i = 0; i < N; i++) { V[i] = scanner.nextLong(); } System.out.println(knapsack(N, c, W, V)); } }

附:如果你想要查看本题数据,可以用下面程序生成近似数据

from random import * mn, mc, mw, mv = int(3e3), int(3e3), int(1e9), int(5e5) def wriFactory(): idx = 0 def wri(w, v, c): nonlocal idx idx += 1 n = len(w) assert 1<=n<=mn and 1<=c<=mc tx = '%d %d\n' % (n, c) for i in w: assert 1<=i<=mw tx += '%d ' % i tx = tx[:-1] + '\n' for i in v: assert 1<=i<=mv tx += '%d ' % i tx = tx[:-1] + '\n' with open('%d.in' % idx, 'w') as f: f.write(tx) return wri wri = wriFactory() # mn, mc, mw, mv = 500, 500, 500, int(1e7) wri([7, 3, 4, 5], [42, 12, 40, 25], 10) wri([1], [1], 1) wri([1], [1], mc) wri([mw], [mc], mc) wri([58], [580], 58) wri([58], [580], 57) wri([58], [580], 59) w = [1 for i in range(mn)] v = [mv for i in range(mn)] wri(w, v, mc) wri(w, v, mc - 1) w = [mn for i in range(mn)] v = [mv - i for i in range(mn)] wri(w, v, mc) wri(w, v, mc - 1) for i in range(5): n = randint(1, mn) c = randint(1, mc) w = [randint(1, mw) for i in range(n)] v = [randint(1, mv) for i in range(n)] wri(w, v, c) for i in range(5): n = randint(1, mn) c = randint(1, mc) w = [randint(1, mn) for i in range(n)] v = [randint(1, mv) for i in range(n)] wri(w, v, c)