Cod sursa(job #2765306)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 26 iulie 2021 12:01:27
Problema Energii Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

const int INF = 1e9;

struct object{
    int val, wt;
} v[1001];

int KnapSack(int n, int W){

    int dp[W + 1];

    dp[0] = 0;
    for(int i = 1;i <= W;i++)
        dp[i] = INF;

    for(int i = 1;i <= n;i++) {
        for(int j = W;j >= v[i].wt;j--) {
            dp[j] = min(dp[j], dp[j - v[i].wt] + v[i].val);
        }
    }

    return (dp[W] == INF? -1 : dp[W]);
}


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    Open("energii");

    int N, W;
    cin >> N >> W;

    for(int i = 1;i <= N;i++)
        cin >> v[i].wt >> v[i].val;

    cout << KnapSack(N, W);

    return 0;
}