1 solutions

  • 0
    @ 2024-12-5 18:19:40

    C++ :

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    
    const int N = 1e6 + 10, INF = 0x3f3f3f3f;
    
    int n, V;
    int f[N];
    
    int main() {
    
    	memset(f, 0x3f, sizeof f);
    	f[0] = 0;
    	
    	cin >> n >> V;
    	
    	while(n--){
    		int c, v;
    		cin >> c >> v;
    		for(int j = V; j >= 0; j--){
    			f[j] = min(f[j], f[max(j - v, 0)] + c);
    		}
    	}
    	
    	if(f[V] == INF) cout << "no solution" << endl;
    	else cout << f[V] << endl;
    
    	return 0;
    }
    
    
    
    

    Python :

    # coding=utf-8
    N, L = map(int, input().split())
    dp = [[float('inf')] * (L + 1) for _ in range(N)]
    cost = [0] * N
    weight = [0] * N
    
    for i in range(N):
        cost[i], weight[i] = map(int, input().split())
    
    for i in range(L + 1):
        dp[0][i] = cost[0] if weight[0] >= i else float('inf')
    
    for i in range(1, N):
        for j in range(1, L + 1):
            dp[i][j] = dp[i - 1][j]
            if weight[i] >= j:
                dp[i][j] = min(dp[i][j], cost[i])
            else:
                dp[i][j] = min(dp[i][j], dp[i - 1][j - weight[i]] + cost[i])
    
    if dp[N - 1][L] == float('inf'):
        print('no solution')
    else:
        print(dp[N - 1][L])
    
    • 1

    Information

    ID
    9171
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By