Cod sursa(job #2178317)

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

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

int p;
#define dim 100000
char buff[dim];

void read(int &nr){
    nr = 0;
    while (buff[p] < '0' || buff[p] > '9')
        if (++p == dim) fread(buff, 1, dim, stdin), p = 0;
    while (buff[p] >='0' && buff[p] <='9'){
        nr = nr*10 + buff[p] - '0';
        if (++p == dim) fread(buff, 1, dim, stdin), p = 0;
    }
}

int main(){
    freopen("energii.in", "r", stdin);
    freopen("energii.out", "w", stdout);
    read(n); read(w);
    for (int i=1; i<=n; i++) read(a[i].x), read(a[i].y);
    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-1][j+a[i].x]?dp[i-1][j] + a[i].y:min(dp[i-1][j+a[i].x], dp[i-1][j] + a[i].y));
            }
        }
    }
    cout << (ans == 1e9?-1:ans);
    return 0;
}