Cod sursa(job #1713517)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 5 iunie 2016 19:51:10
Problema Energii Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("energii.in");
ofstream out("energii.out");

const int DIM = 100000;
vector<pair<int,int> > G;
int N,W;
long long int *WS;
long long int energy = 0;
char buff[DIM];
int pos = 0;

void Read(int &a)
{
    while(!isdigit(buff[pos]))
        if(++pos==DIM)
        in.read(buff,DIM),pos = 0;
    a = 0;
    while(isdigit(buff[pos]))
    {
        a = a*10 + buff[pos]-'0';
        if(++pos==DIM)
            in.read(buff,DIM),pos = 0;
    }
}

int main()
{
    Read(N);
    Read(W);
    int en,co;
    for(int i=1;i<=N;i++)
    {
        Read(en);
        Read(co);
        G.push_back(make_pair(en,co));
        energy+=en;
    }
    in.close();
    if(energy < W)
    {
        out<<-1<<"\n";
        return 0;
    }
    WS = new long long int[energy+1];
    for(int i=0;i<=energy;i++)
        WS[i] = 0;
    long long int maxx = 0;
    long long int best = (1<<30);
    for(int i=0;i<N;i++)
        for(int j=maxx;j>=0;j--)
            if((WS[j] || j==0) && (WS[j+G[i].first]==0 || WS[j+G[i].first] > WS[j] + G[i].second))
            {
                WS[j+G[i].first] = WS[j] + G[i].second;
                if(j+G[i].first >= W && WS[j+G[i].first]<=best)
                    best = WS[j+G[i].first];
                if(maxx < j + G[i].first && j + G[i].first<=W)
                    maxx = j + G[i].first;

            }
    out<<best<<"\n";
    delete[] WS;
    return 0;
}