Cod sursa(job #736512)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 18 aprilie 2012 20:48:44
Problema Energii Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.27 kb

#include <fstream>
#include <cmath>

const unsigned short SIZE(5002);
unsigned int matrix [SIZE - 1] [SIZE];

int main (void)
{
    unsigned int n,g;
    std::ifstream input("energii.in");
    input >> n >> g;
    unsigned int p,c;
    input >> p >> c;
    matrix[1][p] = c;
    unsigned int i(1),j,last(p);
    do
    {
        input >> p >> c;
        if (!matrix[i][p])
            matrix[i + 1][p] = c;
        else
            matrix[i + 1][p] = std::min(matrix[i][p],c);
        j = 1;
        do
        {
            if (matrix[i][j])
            {
                if (!matrix[i][j + p])
                    matrix[i + 1][j + p] = matrix[i][j] + c;
                else
                    matrix[i + 1][j + p] = std::min(matrix[i][j + p],matrix[i][j] + c);
            }
            ++j;
        }
        while (j <= last);
        last += p;
        ++i;
    }
    while (i < n);
    input.close();
    unsigned int result(-1);
    unsigned int *it(matrix[n] + g - 1), *limit(matrix[n] + last);
    while (it <= limit)
    {
        if (*it && *it < result)
            result = *it;
        ++it;
    }
    std::ofstream output("energii.out");
    if (result & (1 << 31))
        output << "-1";
    else
        output << result;
    output.put('\n');
    output.close();
    return 0;
}