Cod sursa(job #2178264)

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

int n, w, dp[1010][5010], s[1010], 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), s[i] = s[i-1] + a[i].x;
    for (int i=1; i<=n; i++){
        for (int j=1; j<=w; j++) dp[i][j] = 1e9;
    }
    for (int i=1; i<=n; i++){
        for (int j=0; j<=s[i-1]; j++){
            if (j + a[i].x >= w) ans = min(ans, dp[i][j] + a[i].y);
            else dp[i][j + a[i].x] = min(dp[i][j + a[i].x], dp[i][j] + a[i].y);
        }
    }
    cout << (ans == 1e9?-1:ans);
    return 0;
}