Cod sursa(job #2178341)

Utilizator Constantin.Dragancea Constantin Constantin. Data 19 martie 2018 13:04:59
Problema Energii Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;

int n, w, dp[1010][5010], s, ans = 1e9;
pair <int,int> a[1010];
#define x first
#define y second

int main(){
    ifstream cin ("energii.in");
    ofstream cout ("energii.out");
    cin >> n >> w;
    for (int i=1; i<=n; i++) cin >> a[i].x >> a[i].y, s += a[i].x;
    for (int i=1; i<=n; i++){
        for (int j=0; j<w; j++){
            if (dp[i-1][j] || !j){
                if (!dp[i][j]) dp[i][j] = dp[i-1][j];
                else dp[i][j] = min(dp[i][j], dp[i-1][j]);
                if (j + a[i].x >= w) ans = min(ans, dp[i-1][j] + a[i].y);
                else dp[i][j + a[i].x] = (!dp[i][j+a[i].x]?dp[i-1][j] + a[i].y:min(dp[i][j+a[i].x], dp[i-1][j] + a[i].y));
            }
        }
    }
    if (s < w) cout << -1;
    else cout << ans;
    return 0;
}