Cod sursa(job #1992364)

Utilizator alex_HarryBabalau Alexandru alex_Harry Data 20 iunie 2017 11:46:11
Problema Ghiozdan Scor 100
Compilator cpp Status done
Runda Lista lui wefgef Marime 1.5 kb
#include <fstream>
using namespace std;
ifstream f("ghiozdan.in");
ofstream g("ghiozdan.out");
const int GMax = 75005;
const int WMax = 205;
int N, G, MaxW;
int From[GMax], DP[GMax], W[WMax], Q[GMax];
void Read()
{
    f >> N >> G;
    for(int i = 1; i <= N; i++)
    {
        int val;
        f >> val;
        MaxW = max(MaxW, val);
        W[val]++;
    }
}

void initialize()
{
    for(int i = 1; i <= G; i++)
        DP[i] = GMax;
}

void Solve()
{
    for(int w = MaxW; w >= 1; w--)
    {
        if(W[w] == 0)
            continue;
        for(int i = G - w; i >= 0; i--)
        {
            if(DP[i] == GMax)
                continue;
            for(int j = w + i, cnt = 1; j <= G && cnt <= W[w]; j += w, cnt++)
            {
                if(DP[j] > DP[i] + cnt)
                {
                    DP[j] = DP[i] + cnt;
                    From[j] = w;
                    Q[j] = cnt;
                }
                else
                    break;
            }
        }
    }
}

void Print()
{
    int H;
    for(int i = G; i >= 1; i--)
    {
        if(DP[i] != GMax)
        {
            H = i;
            break;
        }
    }
    int w = H;
    g << H << " " << DP[H] << "\n";
    while(w > 0)
    {
        int next = w - From[w] * Q[w];
        for(int i = 1; i <= Q[w]; i++)
            g << From[w] << "\n";

        w = next;
    }
}
int main()
{
    Read();
    initialize();
    Solve();
    Print();
    return 0;
}